
本文讲解如何改造基础字典型售货机程序,使其支持用户为同一商品多次添加(如购买2支口红),并准确按数量计算购物车总价,同时保持代码简洁易懂,适合编程入门学习。
本文讲解如何改造基础字典型售货机程序,使其支持用户为同一商品多次添加(如购买2支口红),并准确按数量计算购物车总价,同时保持代码简洁易懂,适合编程入门学习。
当前代码使用 makeup_cart = [] 以列表形式记录商品名称(如 ['lipstick', 'lipstick', 'eyeshadow']),这正是实现“多数量选购”的关键基础——它天然允许重复项。但原逻辑仅简单追加字符串,未做合法性校验;而总价计算不能直接遍历 makeup.items()(那会累加所有商品单价,而非用户实际所购),必须基于购物车内容动态统计。
✅ 正确实现多数量选购与总价计算
首先,在选项 b(添加商品)中增强健壮性:检查用户输入是否真实存在于商品字典中,避免无效添加:
elif choice == "b":
item = input("Enter a makeup item to add: ").strip().lower() # 统一转小写+去空格
if item in makeup:
makeup_cart.append(item)
print(f"{item.capitalize()} has been added to the cart.")
else:
print("Invalid item. Please choose from the menu.")
其次,选项 c(查看购物车)应清晰展示每种商品的数量及单价,便于用户核对:
elif choice == "c":
if not makeup_cart:
print("The makeup cart is empty.")
else:
print("\nMakeup Cart:")
# 使用字典统计各商品出现次数
cart_summary = {}
for item in makeup_cart:
cart_summary[item] = cart_summary.get(item, 0) + 1
total = 0
for item, qty in cart_summary.items():
price = makeup[item]
line_total = price * qty
total += line_total
print(f" {qty} × {item:<p>最后,选项 d(结账)可复用上述统计逻辑,并清空购物车(可选):</p><pre class="brush:php;toolbar:false;">elif choice == "d":
if not makeup_cart:
print("Your cart is empty. Add items before checking out.")
else:
# 同上 cart_summary + total 计算逻辑
cart_summary = {}
for item in makeup_cart:
cart_summary[item] = cart_summary.get(item, 0) + 1
print("\n--- CHECKOUT ---")
total = 0
for item, qty in cart_summary.items():
price = makeup[item]
line_total = price * qty
total += line_total
print(f"{qty} × {item:<h3>⚠️ 注意事项与改进建议</h3>
- 不要用 len(makeup) 计算总价:len(makeup) 返回字典键的数量(如10),与价格完全无关,原文案中的建议是错误的。
- 避免变量名冲突:原答案中使用 sum 作为变量名会覆盖 Python 内置函数 sum(),应改用 total 等更安全的名称。
- 统一输入处理:使用 .strip().lower() 消除大小写和空格差异,提升用户体验。
- 购物车结构进阶提示(可选延伸):未来可将购物车改为 [{'item': 'lipstick', 'qty': 2}, ...] 的字典列表,更直观且易于扩展(如支持修改数量),但对入门项目非必需。
通过以上调整,程序即可自然支持“买2支口红+1盘眼影= $8×2 + $2 = $18”的精准计价,逻辑清晰、改动最小,完美契合入门课程的教学目标。











