当打印“你闻到有趣的特朗普!”时,我想停止while循环。该代码确实停止了,但是并没有停止在正确的句子上,我在这里做错了什么?
while True:
from time import sleep
from random import randint
greetings = ["Hello","Howdy","You smell funny"]
title = ["Human.", "Trump!" , "Maid."]
greeting = "{x}, {y}".format(x=greetings[randint(0,2)], y=title[randint(0,2)])
if greeting == "{x}, {y}".format(x=greetings[2], y=title[1]):
break
else:
sleep(0.3)
print(greeting)
答案 0 :(得分:1)
当它碰到break
并停止循环时,它尚未打印“问候语”。只需将print(greeting)
移动到if greeting == ...
之前即可。
答案 1 :(得分:1)
您可以使用标志而不是'break'退出循环。
Break_Flag=True
while Break_Flag:
from time import sleep
from random import randint
greetings = ["Hello","Howdy","You smell funny"]
title = ["Human.", "Trump!" , "Maid."]
greeting = "{x}, {y}".format(x=greetings[randint(0,2)], y=title[randint(0,2)])
if greeting == "{x}, {y}".format(x=greetings[2], y=title[1]):
print(greeting,"Stop")
Break_Flag=False
else:
sleep(0.3)
print(greeting)