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

Python求和报错求助:新手编写商品总价计算代码遇问题

问题分析与解决方向

你的代码主要有两个核心问题导致求和失败:

  • 变量覆盖问题:sum_变量在每次while循环里都会被新输入的商品价格替换,根本没保存之前输入的价格,自然没法累积求和。
  • sum()函数用法错误:Python的sum()函数需要传入可迭代对象(比如列表、元组这类包含多个元素的集合),你直接传单个整数sum_会触发报错,因为整数不是可迭代的。

两种修正方案(适合新手理解)

方案1:用累加变量逐步计算总价

初始化一个总价变量,每次输入商品价格后,把价格加到这个变量里,循环结束后再打印总价:

number_of_items = int(input('How many items do you have: '))
x = 0
total = 0  # 初始化总价变量

if number_of_items == 0:
    print('Are you not buying anything? ')
elif number_of_items > 10:
    print('Sorry we only accept 10 items or less')
else:
    while x < number_of_items:
        x += 1
        price = int(input(f'Cost of item {x}: '))
        total += price  # 把当前价格加到总价里
    print(f'Total cost: {total}')  # 循环结束后打印总价

方案2:用列表存储所有价格,最后用sum()求和

先把所有输入的价格存到列表里,循环结束后用sum()计算列表的总和:

number_of_items = int(input('How many items do you have: '))
x = 0
prices = []  # 初始化空列表存储价格

if number_of_items == 0:
    print('Are you not buying anything? ')
elif number_of_items > 10:
    print('Sorry we only accept 10 items or less')
else:
    while x < number_of_items:
        x += 1
        price = int(input(f'Cost of item {x}: '))
        prices.append(price)  # 将价格添加到列表
    total = sum(prices)  # 用sum()计算列表所有元素的和
    print(f'Total cost: {total}')

另外注意你的原代码里elif number_of_items > 10:下面的print语句没有缩进,这会触发语法错误,修正后的代码已经补上了缩进。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 06:22:35