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

Python中sum()函数TypeError:不支持int与str相加的问题排查

Python成绩均值计算报错问题分析

新学期开始,我正在做一个简单项目重新熟悉Python。编写的代码如下:

import math
count = input('Please enter the number of grades: ')

grade_list = []

while count != 0:
    grade = input('What was the grade for the first test?: ')
    grade_list.append(grade)
    count = int(count) - 1

def mean(x):
    grade_total = int(sum(x))
    grade_count = int(len(x))
    mean = int(grade_total) / int(grade_count)
    return mean

print(mean(grade_list))

运行时持续出现如下错误:

Traceback (most recent call last):
  File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 17, in <module>
    print(mean(grade_list))
  File "C:\Users\hattd\Documents\Python Projects\miniproject1.py", line 12, in mean
    grade_total = int(sum(x))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我本以为将变量转为整数就能避免该问题,请问我忽略了什么?


问题根源

你忽略了两个核心问题:

  1. 成绩输入未转整数:input()返回的是字符串类型,你直接把grade存入grade_list,导致列表里全是字符串。sum()函数求和时初始值是0(整数),尝试和字符串相加就触发了类型错误——你在mean函数里的int(sum(x))转换太晚,sum(x)本身已经执行失败。
  2. 初始count未转整数:count = input(...)得到的是字符串,while count != 0是字符串和整数比较,逻辑存在隐性bug(比如输入"3"时,第一次循环判断"3" != 0为True,但循环后count变成整数,后续逻辑才正常)。

修复方案

修改两处关键逻辑,同时简化冗余的类型转换:

  1. 输入count时直接转为整数;
  2. 输入成绩时转为整数再加入列表;
  3. 去掉mean函数里多余的int()转换,sum()对整数列表求和结果是整数,len()返回的也是整数。

修改后的完整代码:

count = int(input('Please enter the number of grades: '))

grade_list = []

# 修正循环提示文本,避免每次都显示"first test"
for _ in range(count):
    grade = int(input('What was the grade for this test?: '))
    grade_list.append(grade)

def mean(x):
    grade_total = sum(x)
    grade_count = len(x)
    return grade_total / grade_count

print(mean(grade_list))

另外,把while循环改成for循环更简洁,也避免了手动维护count变量的麻烦。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:34:50