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

Python报错TypeError: 'str'与'int'不支持//运算,求解决方案

解决计算平均分的TypeError错误

错误原因

input()函数返回的是字符串类型,你当前的代码直接对这些字符串执行加法操作,实际是做字符串拼接(比如输入80和90,score1+score2会得到"8090"),之后用这个拼接后的字符串和整数5做整除运算,类型不匹配,因此触发TypeError: unsupported operand type(s) for //: 'str' and 'int'。

修正方案

基础修正版

将每个input()的结果转换为数值类型(整数用int(),带小数的分数用float()),再进行计算:

# 转换为整数(适用于整数分数)
score1 = int(input("enter your math score: "))
score2 = int(input("enter your science score: "))
score3 = int(input("enter your physics score: "))
score4 = int(input("enter your statistics score: "))
score5 = int(input("enter your geometry score : "))
average = (score1 + score2 + score3 + score4 + score5) // 5
print(average)

如果需要保留小数平均分,改用float()转换并使用普通除法:

score1 = float(input("enter your math score: "))
score2 = float(input("enter your science score: "))
score3 = float(input("enter your physics score: "))
score4 = float(input("enter your statistics score: "))
score5 = float(input("enter your geometry score : "))
average = (score1 + score2 + score3 + score4 + score5) / 5
print(average)

优化简洁版

用列表存储科目和分数,避免重复变量,代码更易维护:

subjects = ["math", "science", "physics", "statistics", "geometry"]
# 批量获取并转换分数
scores = [int(input(f"enter your {subject} score: ")) for subject in subjects]
# 计算平均分,len(scores)自动适配科目数量
average = sum(scores) // len(scores)
print(average)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:44:52