Python代码中While循环未按预期运行问题求助
解决餐厅订单循环无法终止的问题
核心错误分析
你的代码导致循环无法终止有三个关键问题:
capitalize未调用:获取用户输入时,.capitalize没加括号,使Order存储的是方法对象而非格式化后的字符串,永远无法匹配菜单列表。- 循环条件逻辑错误:
while Order not in FoodMenuList or Order not in DrinksMenuList用了or,逻辑上只要内容不同时在两个列表里就会循环——但一个菜品不可能同时属于食物和饮料列表,因此条件永远为真,循环停不下来。 - 循环内未更新
Order变量:重复输入时,仅调用input().capitalize()却未将结果赋值给Order,导致Order始终是初始错误值。
修正后的完整代码
print("Welcome To Femboii's Restaraunt") Name = input("What's Your Name Sir?\n").capitalize() EvilGuys = ["Jack", "Ben", "Maria"] # 初始化变量避免未定义报错 Good_Deeds = 0 Bad_Deeds = 0 if Name in EvilGuys: Evil_Status = input("Are You Evil " + Name + "?\n").capitalize() if Evil_Status == "Yes": Good_Deeds = int(input("How Many Good Deeds Have You Done Today " + Name + "?\n")) Bad_Deeds = int(input("How Many Bad Deeds Have You Done Today " + Name + "?\n")) elif Evil_Status == "No": print("Oh, So You Aren't Evil, Come In You're Welcome!") else: print("Sorry I Didn't Understand You, So Ill Just Take It As A No") if Good_Deeds >= Bad_Deeds: print("Oh, So You Aren't Evil, Come In You're Welcome!") else: print("GET OUTTTT RIGHT NOWWWWWWWWWW!!!!!!!!!!") exit() print("Welcome " + Name) FoodMenu = "Pizza, Crepe, Burger And Shawrma." DrinksMenu = "Black Coffee, Latte, Mocha, Espresso, Crapuccino And Sparkling Water" FoodMenuList = ["Pizza", "Crepe", "Burger", "Shawrma"] DrinksMenuList = ["Black Coffee", "Latte", "Mocha", "Espresso", "Crapuccino", "Sparkling Water"] # 调用capitalize()方法格式化输入 Order = input(f"Here's Our Food Menu\n{FoodMenu}\nAnd Here's Our Drinks Menu\n{DrinksMenu}\nChoose What Serves You The Best.\n").capitalize() # 用and判断:同时不在两个列表才进入循环 while Order not in FoodMenuList and Order not in DrinksMenuList: # 将新输入赋值回Order,更新变量值 Order = input("Sorry, I Didn't Understand What You Said, Can You Repeat?\n").capitalize() print(Order)
额外优化说明
- 新增
Good_Deeds和Bad_Deeds的初始化,避免用户输入"No"或未识别内容时,后续判断出现NameError。 - 用f-string替换字符串拼接,提升代码可读性。
- 删除循环内多余判断,
while条件已过滤合法情况,循环内直接处理非法输入即可。
内容的提问来源于stack exchange,提问作者ObviouslyNotAFemBoy
相关产品推荐
相关产品推荐

