【问题标题】:How should I fix this - 'int' object is not iterable? [closed]我应该如何解决这个问题 - 'int' 对象不可迭代? [关闭]
【发布时间】:2020-04-01 19:44:42
【问题描述】:

与其他问题不同,我遇到了这个错误没有使用循环构造。

这是代码

def makes_twenty(n1,n2):
    return ( (sum(n1, n2) == 20) or ((n1 == 20) or (n2 == 20)) )

我收到的错误 - 'int' object is not iterable Screenshot of the code with error

讽刺的是,如果我改变这件事—— sum(n1, n2) 变成这样的东西 - (n1 + n2) 代码工作正常。 Screenshot of corrected code 我想知道这里发生了什么。

【问题讨论】:

  • sum 尝试迭代其第一个参数,例如sum([n1, n2])(甚至sum([n1], n2)!)可以正常工作。这并不讽刺,这就是它被记录为工作的方式。
  • 请不要发布代码、数据或 Tracebacks 的图像。只需复制文本,将其粘贴到您的问题中并将其格式化为代码即可。
  • 在其docs page 中阅读有关sum 的信息,那里已经解释得很好......另外,如果您只有2 个数字,为​​什么还要使用sum?无论如何,您的第二个选项n1+n2 似乎更清楚

标签: python python-3.x function sum int


【解决方案1】:

python 中的sum 函数将第一个参数作为可迭代对象。您可以在sum([n1, n2]) 之类的列表中传递n1n2。由于n1 是整数sum 函数不能循环它因此错误'int' object is not iterable

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 2020-02-14
    相关资源
    最近更新 更多