自动售货机金额统计问题:列表追加值并求和失败
问题分析与修复方案
核心问题:total列表始终为空的原因
- 错误的匹配逻辑:代码中
if productkeys[choice_index] == key:里的key是之前遍历商品字典时最后一个键(比如你的商品列表最后一个是"Peanut Butter Kit-Kat",所以key固定为这个值),只有用户选到这个特定商品时才会触发追加操作,其他商品都不会加入total。 - 第一次选品未计入total:初始的try块里只把选品加入了order,没同步加到total。
- sum(total)未保存结果:即使追加了价格,
sum(total)只是计算但没有赋值给变量,最后打印的还是空列表。 - 循环逻辑混乱:内层while里的break位置不对,可能导致逻辑提前终止。
修复后的完整代码
import sys products = {"Water": 1.00, "Chocolate Chip Cookie": 1.00, "Cheese and Onion Crisps": 1.10, "Cream Soda": 0.70, "Chicken Sandwich": 2.60, "M&ms": 1.50, "Peanut Butter Kit-Kat": 1.10} # 打印商品列表 position = -1 for key in products: position += 1 print(position, " ", key, products[key]) productkeys = list(products.keys()) order = [] total = [] print("\nselect a number for the item you want") # 处理第一次选品 try: choice_index = int(input("Enter Vending item number: ")) selected_item = productkeys[choice_index] print(selected_item) order.append(selected_item) total.append(products[selected_item]) except IndexError: print("wrong index") # 若第一次输入错误,进入循环让用户重新选择 choice_index = -1 # 后续选品循环 while True: choice_index = int(input("Enter Vending item number: 9 to exit")) if choice_index == 9: break if choice_index not in range(len(productkeys)): print("wrong index") continue selected_item = productkeys[choice_index] print(selected_item) order.append(selected_item) total.append(products[selected_item]) # 最终结算 total_amount = sum(total) print(f"Thanks for your selection: {order}, Total = {total_amount:.2f}")
关键修复点
- 移除无效的key匹配:直接通过
productkeys[choice_index]获取选中的商品,再从字典中取对应价格加入total。 - 统一选品逻辑:第一次选品和后续循环都同步更新order和total列表。
- 正确计算并展示总金额:用
sum(total)计算总金额,保留两位小数输出,而不是打印列表。 - 简化循环结构:去掉嵌套while,用单循环+continue处理错误输入,逻辑更清晰。
- 修正拼写错误:把原代码里的"Ceeam Soda"改为"Cream Soda",避免后续可能的问题。
内容的提问来源于stack exchange,提问作者Peter Brown
相关产品推荐
相关产品推荐

