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

Python求和报错:TypeError: int与str类型不支持+运算

问题分析与修复方案

错误原因

  • 你每次循环都把新输入的数字赋值给numbers,导致之前输入的数字全被覆盖,最后numbers只剩最后一个输入的数。
  • 把单个数字转成字符串再split,得到的是字符串类型的列表,而sum()函数只能对数字类型求和,因此触发类型错误。
  • 循环外部的break语句完全多余,for循环本身会按你输入的次数执行完毕,这行代码根本不会被触发。

修复方案

方法一:用列表存储所有输入的数字

这种方式直观,适合需要保留所有输入数字的场景:

input_num = int(input('How many numbers will you enter?: '))
numbers = []
for n in range(1, input_num + 1):
    num = int(input(f'Enter number {n}: '))
    numbers.append(num)

print(sum(numbers))

方法二:边输入边累加

这种方式更节省内存,不需要存储所有数字,适合处理大量输入的情况:

input_num = int(input('How many numbers will you enter?: '))
total = 0
for n in range(1, input_num + 1):
    num = int(input(f'Enter number {n}: '))
    total += num

print(total)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:52:01