什么是非常简单的 while 循环语句,它将继续下面的程序直到用户键入“exit”?
例如,
while response = (!'exit')
continue file
else
break
print ('Thank you, good bye!')
#I know this is completely wrong, but it's a try!
到目前为止我的文件:
#!/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: "
请您参考如下方法:
continue 是一个不需要参数的关键字。它只是告诉当前循环立即继续下一次迭代。它可以在 while 和 for 循环中使用。
然后您的代码应置于 while 循环中,该循环将一直运行直到满足条件。您的条件语法不正确。它应该显示为 while response != 'exit':。因为您正在使用条件,所以不需要 continue 语句。只要值不是 "exit",它就会按设计继续。
您的结构将如下所示:
response = ''
# this will loop until response is not "exit"
while response != 'exit':
response = raw_input("foo")
如果您想使用 continue,如果您要对响应执行其他各种操作,可能会用到它,并且可能需要提前停止并重试。 break 关键字是作用于循环的类似方式,但它表示我们应该立即完全结束循环。您可能有一些其他情况会破坏交易:
while response != 'exit':
response = raw_input("foo")
# make various checks on the response value
# obviously "exit" is less than 10 chars, but these
# are just arbitrary examples
if len(response) < 10:
print "Must be greater than 10 characters!"
continue # this will try again
# otherwise
# do more stuff here
if response.isdigit():
print "I hate numbers! Unacceptable! You are done."
break
