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

Python中计算两数之和时遇TypeError: 'int'对象不可迭代如何解决?

问题解决:TypeError: 'int' object is not iterable

错误原因

你代码里的sum(no1, no2)用法有误,Python内置的sum()函数第一个参数必须是可迭代对象(比如列表、元组),第二个参数是可选的起始值(默认0)。直接传入两个整数时,Python会尝试迭代第一个整数,因此抛出"int对象不可迭代"的错误。

修正方案

方案1:直接用加法运算符计算(最直观)

class Solution:
    def twomakes10(self, no1, no2):
        if no1 + no2 == 10:
            return True
        else:
            return False

if __name__ == "__main__":
    p = Solution()
    n1 = 9
    n2 = 1
    print(p.twomakes10(n1, n2))  # 输出True

方案2:用sum函数(需传入可迭代对象)

如果非要使用sum(),把两个整数放进列表或元组这类可迭代对象中:

class Solution:
    def twomakes10(self, no1, no2):
        if sum([no1, no2]) == 10:
            return True
        else:
            return False

if __name__ == "__main__":
    p = Solution()
    n1 = 9
    n2 = 1
    print(p.twomakes10(n1, n2))  # 输出True

方案3:简化代码(更简洁的写法)

因为比较表达式本身就会返回布尔值,所以可以直接返回判断结果:

class Solution:
    def twomakes10(self, no1, no2):
        return no1 + no2 == 10

if __name__ == "__main__":
    p = Solution()
    n1 = 9
    n2 = 1
    print(p.twomakes10(n1, n2))  # 输出True

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 15:30:50