Python咖啡店程序运行异常求助:总金额计算结果错误
咖啡店订单程序异常修复方案
核心问题诊断
- 金额计算错误:
input()获取的quantity是字符串类型,字符串与数字相乘会执行字符串重复操作(例如"4" * 120会生成120个"4"拼接的字符串),而非数值乘法,导致总金额输出大量重复数字。 - 未定义变量错误:代码中多次调用
coffee[0]、coffee[1]等,但从未定义过coffee变量,实际运行时会触发NameError(当前运行结果未显示是因为程序在报错前已完成了金额打印)。
修复后的完整代码
prices = [120, 130, 120, 150] menu = { 1: ["Latte", 120], 2: ["Capputino", 130], 3: ["Americano", 120], 4: ["Espresso", 150] } headers = ["No.", 'Name', "Price"] print(f'{headers[0]: <10}{headers[1]: <15}{headers[2]}') for value, key in menu.items(): print(f'{value: <10}{key[0]: <15}{key[1]}') myorder_coffee = [] myorder_cost = [] total = 0 print("Welcome to COFFEE & DELIGHT") name = input("Enter your name: ") order = input("Enter the name of your order: ") # 将输入的数量转换为整数,确保数值计算有效 quantity = int(input("Enter the amount of drinks you want to order: ")) if order == "Latte": myorder_coffee.append(order) myorder_cost.append(prices[0]) total = quantity * 120 print(name, "ordered", quantity, "Latte") print("Total amount to be paid=", total) elif order == "Capputino": myorder_coffee.append(order) myorder_cost.append(prices[1]) total = quantity * 130 print(name, "ordered", quantity, "Capputino") print("Total amount to be paid=", total) elif order == "Americano": myorder_coffee.append(order) myorder_cost.append(prices[2]) total = quantity * 120 print(name, "ordered", quantity, "Americano") print("Total amount to be paid=", total) elif order == "Espresso": myorder_coffee.append(order) myorder_cost.append(prices[3]) total = quantity * 150 print(name, "ordered", quantity, "Espresso") print("Total amount to be paid=", total) else: print("Item not in menu")
关键修复说明
- 类型转换:将
quantity的输入值通过int()转为整数类型,保证后续乘法是数值运算而非字符串重复。 - 变量替换:删除对未定义
coffee变量的引用,直接使用用户输入的order字符串添加到订单列表中,逻辑更直接。
可选优化(简化代码)
原有的if-elif链冗余度高,可利用menu字典遍历匹配订单,新增品类时无需修改多个分支:
# 替换原有的if-elif代码块 order_found = False for coffee_info in menu.values(): coffee_name, coffee_price = coffee_info if coffee_name == order: myorder_coffee.append(coffee_name) myorder_cost.append(coffee_price) total = quantity * coffee_price print(f"{name} ordered {quantity} {coffee_name}") print(f"Total amount to be paid= {total}") order_found = True break if not order_found: print("Item not in menu")
内容的提问来源于stack exchange,提问作者Fish pp
相关产品推荐
相关产品推荐

