Python中for循环内累加商品总价计算错误的问题求助
问题分析
你的代码存在三个核心问题导致计算错误:
- 价格计算逻辑错误:
price += price * quantity这个表达式是将当前总价乘以数量后再累加,完全不符合“累加单个商品总价(单价×数量)”的需求。 - 总价变量被错误覆盖:当用户选择购买商品时,你直接用
price = int(input(...))把总价变量替换成了单价,导致之前的累加结果丢失。 - 计算触发时机错误:无论商品是否被购买,循环末尾都会执行价格累加,这会把未购买的商品也计入总价。
修正后的代码
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
相关产品推荐
相关产品推荐

