简体   繁体   English

满足条件时while循环不会停止

[英]While loop does not stop when the condition is met

I want to stop this while loop when it prints "You smell funny Trump!".当它打印“你闻起来很有趣特朗普!”时,我想停止这个 while 循环。 The code does stop, but it does not stop at the right sentence, what did I do wrong here?代码确实停止了,但它没有停在正确的句子上,我在这里做错了什么?

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)

It does not have printed the "greeting" yet, when it hits the break and stops the loop.当它遇到break并停止循环时,它还没有打印“问候语”。 Just move the print(greeting) to just before the if greeting == ... .只需将print(greeting)移动到if greeting == ...

You may use a Flag instead of 'break' to exit loop.您可以使用 Flag 而不是 '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)    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM