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

如何修正Python程序,实现购物清单商品总价的正确计算与输出?

问题解决

你的代码问题在于print(total)放在了for循环内部,导致每次累加后都会打印当前的total值,最终输出会是1和3,而不是只输出最终总价。

修正方法很简单,把print(total)移到循环外面,确保循环结束后只打印一次最终的总价:

total = 0
for particular_items in shopping_list:
    total += prices_and_their_products.get(particular_items)
print(total)

另外,为了避免购物清单中出现字典里没有的商品时抛出错误(get方法找不到键会返回None,和整数相加会报错),可以给get方法加上默认值0,让程序更健壮:

total = 0
for particular_items in shopping_list:
    total += prices_and_their_products.get(particular_items, 0)
print(total)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:20:31