You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环异常:自助点餐系统重复交互逻辑故障求助

麦当劳自助点餐系统循环逻辑修复

问题根源分析

  • 内层循环条件逻辑错误:原代码内层while循环用or连接多个不等于判断,这会导致条件永远为真(任何输入不可能同时等于"Yes"/"yes"/"No"/"no"四个值),循环无法按预期退出。
  • 终止逻辑不完整:输入"No"/"no"时仅跳出内层循环,外层while True仍会继续执行,无法终止整个程序。
  • 变量初始化错误:repeat初始值为整数0,与后续输入的字符串类型比较会引发逻辑异常。

修复后的完整代码

import time

burger = 0
mcpuff = 0
icecream = 0
coldrink = 0
repeat = ""  # 初始化为空字符串,避免类型不匹配
price = 0

print("Welcome to McDonald's self order system")
time.sleep(0.5)
name_person = str(input("\nPlease enter your name to continue: "))

while True:
    try:  # 新增异常处理,防止输入非数字导致崩溃
        order = int(input("""
---Menu---
 1.Burger
 2.McPuff
 3.Ice Cream
 4.Cold Drink

Please order by typing the number: """))
    except ValueError:
        print("\n!!Invalid input!! Please enter a number between 1-4.")
        time.sleep(0.5)
        continue

    if order in range(1, 5):
        try:
            order_amount = int(input("Please enter the amount you want to order: "))
        except ValueError:
            print("\n!!Invalid input!! Please enter a valid number.")
            time.sleep(0.5)
            continue
        
        if order == 1:
            burger += order_amount
        elif order == 2:
            mcpuff += order_amount
        elif order == 3:
            icecream += order_amount
        elif order == 4:
            coldrink += order_amount
        
        # 重构内层循环条件,仅当输入不在指定范围内时循环
        while repeat not in ("Yes", "yes", "No", "no"):
            repeat = input("Do you want to order more? Yes/No: ")
            if repeat in ("Yes", "yes"):
                repeat = ""  # 重置状态,回到点餐菜单
                break
            elif repeat in ("No", "no"):
                print("Ok")
                # 终止所有循环
                break
            else:
                print("\n!!Invalid input!!")
                time.sleep(0.5)
        else:
            # 内层循环正常退出(输入Yes),继续外层循环
            continue
        # 输入No时,跳出外层循环
        break
    else:
        print("\n!!Invalid input!!")
        time.sleep(0.5)

# 可选:添加订单汇总打印
print(f"\n--- Order Summary for {name_person} ---")
print(f"Burger: {burger}")
print(f"McPuff: {mcpuff}")
print(f"Ice Cream: {icecream}")
print(f"Cold Drink: {coldrink}")
print("Ok")

关键修改说明

  • 内层循环条件优化:将错误的or判断改为repeat not in ("Yes", "yes", "No", "no"),逻辑更清晰且正确。
  • 完整终止逻辑:输入"No"/"no"时,先处理内层循环,再通过break跳出外层while True循环,彻底终止程序。
  • 类型匹配修复:将repeat初始值设为空字符串,避免整数与字符串的无效比较。
  • 新增异常处理:添加try-except捕获输入非数字的情况,防止程序崩溃,提升鲁棒性。
  • 订单汇总(可选):添加订单汇总打印,让功能更完整。

内容的提问来源于stack exchange,提问作者CreeperOnCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:54:28