Python While循环不断重复

2024-05-28 20:57:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用我创建的这个程序,我希望这个程序不要重复这个选项很多次这里是程序:

 # A Program to show how to use a menu
 menu=int(input("What would you like? \n\
 1. A compliment \n\
 2. An insult \n\
 3. A proverb \n")) 
 y=True
 while y==True:
     if menu==1: #compliment
           print ("You look nice today")
     elif menu==2: #insult
           print("You smell")
     elif menu==3: #proverb
           print("A bird in the hand is worth two in the bush!")
     else:
          y==False
          print("Invalid option")
          break

结果是,当我输入选项(例如2)时,程序会重复 你闻到了吗 你闻到了吗 你闻到了吗 你闻到了吗 你闻到了吗 无限次。在


Tags: thetoin程序youtrue选项show
2条回答

你的while循环永远不会结束。您在最后的“else”下有一个中断,但您假设您的变量menu将实际被修改。您不应该在响应上循环,而是应该这样整体:

y=True
while y==True:
    menu=int(input("What would you like? \n\
    1. A compliment \n\
    2. An insult \n\
    3. A proverb \n")) 

    if menu==1: #compliment
       print ("You look nice today")
    elif menu==2: #insult
       print("You smell")
    elif menu==3: #proverb
       print("A bird in the hand is worth two in the bush!")
    else:
       print("Invalid option ")
       y = False

上述操作将一直运行,直到输入无效选项,然后循环将中断。由于y永远无法修改,所以原始代码永远不会中断。您的y==False是比较操作,而不是赋值操作。但是,这仍然不会被命中,因为您没有在循环中请求额外的输入,所以它将永远保持TRUE。在

问题2。正如@Arrjun Ram提到的,当您需要y=False时,您有{}

另一个问题是对input的调用在while循环之外。这意味着菜单的值永远不会改变。您需要将它移到while循环的内部。在

您还可以添加一个选项,比如4,以退出循环。在

相关问题 更多 >

    热门问题