下面有一个包含while循环的小代码.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"如果我输入"normal",程序就会打印Ok。你的心情很正常。无数次。
但是如果我输入“很好”,程序就会打印Ok。你的心情很正常。并打印question_2的内容。
为什么question_2 = raw_input("How are you 2? > ")中的问题没有重复无数次?
得出raw_input()停止无限时间循环的结论是否合理?
发布于 2015-07-12 07:25:45
一旦你回答了“很好,第二个raw_input返回的值将被存储在变量question_2中而不是问题中。所以变量问题永远不会改变,但是会保持”好“。所以不管你回答什么,你都会继续点击第二个raw_input。它不会停止你的循环,而是暂停它直到你回答。我认为你也应该好好看看阿尔法辛的评论……
发布于 2015-12-18 21:47:14
您可以通过使用else或elif输出break来停止无限循环。希望这能帮上忙!
示例:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break 发布于 2015-07-12 07:24:18
raw_input()不会中断循环。它只是在等待输入。而且,由于您的question没有被第二个raw_input()覆盖,所以您的if块将始终在good情况下结束。
另一种方法:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?https://stackoverflow.com/questions/31365392
复制相似问题