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'.