python while break try 无法中断_简单的while循环,直到在Python中中断

What would a very simple while loop statement be that would continue the below program until the user types "exit"?

For example,

while response = (!'exit')

continue file

else

break

print ('Thank you, good bye!')

#I know this is completely wrong, but it's a try!

My file so far:

#!/usr/bin/python

friends = {'John' : {'phone' : '0401',

'birthday' : '31 July',

'address' : 'UK',

'interests' : ['a', 'b', 'c']},

'Harry' : {'phone' : '0402',

'birthday' : '2 August',

'address' : 'Hungary',

'interests' : ['d', 'e', 'f']}}

response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()

try:

print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])

except KeyError:

print "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

解决方案

Your while loop will continue until the condition you've set is false. So you want your code to mostly be inside this loop. Once it's finished, you know the user entered 'exit' so you can print the error message.

#!/usr/bin/python

friends = {'John' : {'phone' : '0401',

'birthday' : '31 July',

'address' : 'UK',

'interests' : ['a', 'b', 'c']},

'Harry' : {'phone' : '0402',

'birthday' : '2 August',

'address' : 'Hungary',

'interests' : ['d', 'e', 'f']}}

response = ['']

error_message = "Sorry, I don't know about that. Please try again, or type 'exit' to leave the program: "

while response[0] != 'exit':

response = raw_input("Please enter search criteria, or type 'exit' to exit the program: ").split()

try:

print "%s's %s is %s" % (response[0], response[1], friends[response[0]][response[1]])

except KeyError:

print error_message

except IndexError:

print error_message

print ('Thank you, good bye!')

This code is a start to what you want, but it still has some bugs. See if you can restructure it so the error message isn't printed when the user enters 'exit'.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值