首页 > 解决方案 > 用户按下所有答案后如何在python中结束循环?

问题描述

# loop
while True:
  inp = raw_input()
  if inp == "":pres= input("What would you like to know about me? AGE, JOKE, FACT")
  if pres in {'AGE', 'Age','age'}:
    print("I was birthed from my mother 87 years ago. Press enter to continue")
  if pres in {'JOKE','Joke','joke'}:
    print("Where do polar bears keep their money?")
    import time
    time.sleep(2)
    print("In a snow bank! Press enter to continue")
  if pres in {'FACT','Fact','fact'}:
    print("Hippopotamus's have pink spit! Press enter to continue")

# end of loop

我试图结束这个循环,但最后使用 break 似乎不起作用。我希望在用户输入所有三个选项后结束循环;年龄、笑话和事实。

标签: pythonloops

解决方案


您可以在一组中记录用户查询的状态:

chosen = set()
while len(chosen) < 3:
    inp = raw_input()
    if inp == "":
        pres = input("What would you like to know about me? AGE, JOKE, FACT")
    if pres in {'AGE', 'Age','age'}:
        print("I was birthed from my mother 87 years ago. Press enter to continue")
        chosen.add("age")
    if pres in {'JOKE','Joke','joke'}:
        print("Where do polar bears keep their money?")
        import time
        time.sleep(2)
        print("In a snow bank! Press enter to continue")
        chosen.add("joke")
    if pres in {'FACT','Fact','fact'}:
        print("Hippopotamus's have pink spit! Press enter to continue")
        chosen.add("fact")

推荐阅读