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

Python中for循环内累加商品总价计算错误的问题求助

问题分析

你的代码存在三个核心问题导致计算错误:

  1. 价格计算逻辑错误:price += price * quantity 这个表达式是将当前总价乘以数量后再累加,完全不符合“累加单个商品总价(单价×数量)”的需求。
  2. 总价变量被错误覆盖:当用户选择购买商品时,你直接用price = int(input(...))把总价变量替换成了单价,导致之前的累加结果丢失。
  3. 计算触发时机错误:无论商品是否被购买,循环末尾都会执行价格累加,这会把未购买的商品也计入总价。
修正后的代码
items = []
purchased_i = []
total_price = 0  # 改名更清晰,避免和单价混淆
shop = input("Enter the shop you are visiting: ")
count = int(input("How many items do you want to add?"))

for i in range(count):
    choice = input("Enter your item: ")
    quantity = int(input("How many do you need?: "))
    purchased = input("Have you purchased this item(s)?: ")

    if purchased.lower() == "yes": 
        purchased_i.append(choice)  # 修正:存储商品名而非"yes"
    elif purchased.lower() == "no":
        items.append(choice)
        choice2 = input("Would you like to purchase this item(s)?: ")
        if choice2.lower() == "yes":
            unit_price = int(input("How much would you be willing to pay per item(s)?: £"))
            # 累加当前商品的总价:单价×数量
            total_price += unit_price * quantity
        print("The priority for this item is", len(items))

print("Your total price is £", total_price)
关键修改说明
  • 将总价变量改名为total_price,和临时的unit_price(单价)区分开,避免变量混淆。
  • 用临时变量unit_price存储单个商品的单价,不再覆盖总价变量,保留之前的累加结果。
  • 仅当用户确认购买该商品时,才计算unit_price * quantity并累加到total_price中,避免无效计算。
  • 修正了purchased_i.append(purchased)的错误,改为存储商品名choice,符合列表存储已购商品的逻辑。

测试你的场景:两次循环都输入单价2、数量2,第一次累加2×2=4,第二次累加2×2=4,最终总价为8,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 21:27:30