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

Python实现购物车应用时如何计算所有商品的含税总金额

购物车总金额计算修改方案

核心修改逻辑

  • 循环遍历前初始化总金额累加变量,初始值为0.0
  • 每次计算完单个商品的含税总价后,将该值累加到总金额变量中
  • 调整打印逻辑适配预期的输出格式,税费为0时简化输出内容
  • 遍历所有商品结束后,打印付款提示和累计的总金额

修改后完整代码

cart = {"Shirt": ["Clothing", 39.99, "Manhattan"], "TV": ["Electronic", 999.00, "White Plains"], "Muffin": ["Bread", 9.50, "Manhattan"], "Jacket": ["Clothing", 45.95, "White Plains"], "Coat": ["Clothing", 239.55, "Manhattan"]}

# 初始化总金额累加变量
total = 0.0

for i in cart:
    unit = cart[i][1]
    city = cart[i][2]
    kind = cart[i][0]
    taxPercent = getTaxRate(city, kind, unit)
    tax = taxPercent * unit
    item_total = unit + tax
    # 累加当前商品总价到总金额
    total += item_total
    # 适配预期格式打印
    print("*Tax: ${:.2f}".format(tax))
    if tax == 0:
        print("{}:  ${:.2f}".format(i, unit))
    else:
        print("{}: {}+${:.2f} = ${:.2f}".format(i, unit, tax, item_total))

# 打印底部总金额
print("---------- Please pay the following ----------")
print("Total:                    ${:.2f}".format(total))

内容的提问来源于stack exchange,提问作者Victória Greco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:36:08