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

Python餐厅菜单程序无法计算总费用问题求助

问题解决:餐厅菜单程序总费用累计失败

问题出在变量初始化的位置:你把totalPrice = 0写在了while True循环内部,每次用户选择菜品时,这个变量都会被重置为0,根本没法累计之前的消费金额。

把totalPrice = 0移到循环外面就能解决,另外还修正了你代码里Cheeseburger价格和菜单不一致的小错误:

print("1. Cheeseburger: $3.50")
print("2. Gyro: $6.00")
print("3. Chicken Sandwich: $2.50")
print("4. Burrito: $7.00")
print("5. Fries: $1.50")
print("6. Exit")

totalPrice = 0  # 移到循环外,只初始化一次
while True:
    choice = input("Enter a choice from 1-6\n")
    if choice == "1":
        price = 3.50
        totalPrice += price
    elif choice == "2":
        price = 6.00
        totalPrice += price
    elif choice == "3":
        price = 2.50
        totalPrice += price
    elif choice == "4":
        price = 7.00
        totalPrice += price
    elif choice == "5":
        price = 1.50
        totalPrice += price
    elif choice == "6":
        print("Exiting...")
        print(f"Total Price: ${totalPrice:.2f}")  # 格式化输出更规范
        break
    else:
        print("Enter a valid choice!")

给个额外的优化建议:用字典存储菜品信息,代码会更简洁易维护,后续加菜改价也更方便:

menu = {
    "1": ("Cheeseburger", 3.50),
    "2": ("Gyro", 6.00),
    "3": ("Chicken Sandwich", 2.50),
    "4": ("Burrito", 7.00),
    "5": ("Fries", 1.50),
    "6": ("Exit", 0)
}

# 打印菜单
for key, (item, price) in menu.items():
    if key != "6":
        print(f"{key}. {item}: ${price:.2f}")
    else:
        print(f"{key}. {item}")

totalPrice = 0
while True:
    choice = input("Enter a choice from 1-6\n")
    if choice in menu:
        if choice == "6":
            print("Exiting...")
            print(f"Total Price: ${totalPrice:.2f}")
            break
        item, price = menu[choice]
        totalPrice += price
        print(f"Added {item} to your order.")
    else:
        print("Enter a valid choice!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:30:51