Skip to main content
 首页 » 编程设计

python之用户按下所有答案后如何在 python 中结束循环

2025年05月04日16del

# 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 似乎不起作用。我希望循环在用户输入所有三个选项后结束;年龄、笑话和事实。

请您参考如下方法:

您可以将用户查询的状态记录在一个集合中:

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")