您的while循环将继续,直到您设置的条件为false。因此,您希望您的代码大部分位于此循环内。完成后,您知道用户输入了“退出”,因此您可以打印错误消息。
#!/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!')
这段代码是您想要的代码的开始,但是仍然存在一些错误。查看您是否可以对其进行重组,以便在用户输入“退出”时不显示错误消息。