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

Python咖啡亭程序:如何对从字典获取的列表元素求和?

咖啡亭自助点餐程序问题修复

核心问题排查

你代码里的sum(order)无法正确计算总价,根源是向order列表添加元素时错误嵌套了子列表:

order.append([coffeeItems.get(itemChoice)])  # 错误:添加的是[价格]这样的子列表

这会让order变成类似[[4.25], [4.99]]的结构,sum()无法直接对包含列表的序列求和,必须改成直接添加数值:

order.append(coffeeItems.get(itemChoice))  # 正确:添加单个浮点数值

修复后完整代码(含多顾客功能+细节优化)

import time 

coffeeItems = {"Hot Brew": 4.25, "Latte": 4.75, "Mocha": 4.99, "Cold Brew": 3.95, "Cappuccino": 4.89, "Donut": 1.50}

# 多顾客循环
while True:
    print("Welcome to the SCC Coffee Shop PAWS!")
    print()
    time.sleep(1)

    # 格式化展示菜单
    print("       Menu")
    print("*"*20)
    for item, price in coffeeItems.items():
        print(f"{item:<15} ${price:.2f}")
    print()

    order = []
    while True:
        itemChoice = input("Please enter the item you would like to purchase or enter 'none' to exit: ").strip()

        if itemChoice.lower() == "none":
            break
        # 统一转小写匹配(避免大小写输入错误)
        matched_item = next((item for item in coffeeItems if item.lower() == itemChoice.lower()), None)
        if not matched_item:
            print("Sorry, we do not currently offer that item.")
        else:
            order.append(coffeeItems[matched_item])
            print(f"Added {matched_item} to your order.")

        anotherItem = input("Would you like to purchase another item? (y/n): ").strip().lower()
        if anotherItem == "y":
            continue
        elif anotherItem == "n":
            break
        else:
            print("Invalid entry. Choosing 'n' to proceed to checkout.")
            break

    # 计算订单总价(处理空订单情况)
    if not order:
        print("No items in your order.")
    else:
        itemTotal = sum(order)
        tax_rate = 0.09
        tax_amount = itemTotal * tax_rate
        subtotal_with_tax = itemTotal + tax_amount

        # 捐赠处理
        while True:
            donation = input("Would you like to donate $5 to the SCC Foundation for student scholarships? (y/n): ").strip().lower()
            if donation == "y":
                donate = 5.0
                break
            elif donation == "n":
                donate = 0.0
                break
            else:
                print("Invalid entry. Please enter 'y' or 'n'.")

        total = subtotal_with_tax + donate
        # 格式化输出账单
        print("\n--- Your Bill ---")
        print(f"Item Total: ${itemTotal:.2f}")
        print(f"9% Tax: ${tax_amount:.2f}")
        print(f"Donation: ${donate:.2f}")
        print(f"Final Total: ${total:.2f}")
        print("-----------------\n")

    # 询问是否接待下一位顾客
    next_customer = input("Is there another customer? (y/n): ").strip().lower()
    if next_customer != "y":
        break
    print("\n" + "-"*30 + "\n")

time.sleep(3)

额外优化说明

  • 修复了大小写不敏感匹配:用户输入"hot brew"也能正确识别商品
  • 增加空订单处理:避免无商品时计算出错
  • 优化菜单展示格式:对齐商品名和价格,更易读
  • 完善输入容错处理:无效输入时给出明确提示并合理跳转
  • 实现多顾客循环:满足题目要求的多顾客使用需求
  • 格式化账单输出:清晰展示各项费用,保留两位小数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:45:07