首页 > 解决方案 > 为什么尝试调用此模块会导致“int object is not iterable”错误?

问题描述

我正在尝试学习如何从不同文件中的模块调用函数。为什么尝试使用返回的值会给我一个“Int object is not iterable”错误?

import totalages



firstage = int(input('enter age: '))
secondage = int(input('enter age: '))

result = sum(firstage, secondage)

print('together you are', result, 'years old')
###################### 这是在一个名为 totalages.py 的单独文件中
def sum(a, b):

    return a + b

当 sum 函数包含在 main.js 中时,代码按预期工作,以添加两个输入。但是,如果我将函数移动到单独的文件并尝试导入结果并调用它,我会收到“int object is not iterable”错误。为什么?

标签: pythonintiterable

解决方案


首先,sum是一个 python 内置函数,所以你应该将你的函数重命名为my_sum

还有两种方法可以导入函数

  1. from totalages import my_sum,它告诉解释器去查看totalages.py并导入函数my_sum,然后你可以直接使用my_sum(a, b)

  2. import totalages你需要做的totalages.my_sum(a,b)

现在在这里发生了什么,您的 import 语句确实起作用了,但是您引用了sum我之前引用的 python 内置函数,它接受像列表一样的可迭代对象,但是由于您传递给它一个整数,所以您看到的错误int object is not iterable如下

In [2]: sum(1+2)                                                                                                                                      
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-6576b93b138f> in <module>
----> 1 sum(1+2)

TypeError: 'int' object is not iterable

因此,请记住所有这些,您的原始代码将更改为

#Corrected import statement
from totalages import my_sum

firstage = int(input('enter age: '))
secondage = int(input('enter age: '))

result = my_sum(firstage, secondage)

print('together you are', result, 'years old')

你的 totalages.py 将变为

def my_sum(a, b):

    return a + b

或者如果您使用的另一个选项import totalages

import totalages

firstage = int(input('enter age: '))
secondage = int(input('enter age: '))

result = totalages.my_sum(firstage, secondage)

print('together you are', result, 'years old')

输出将如下所示:

enter age: 20
enter age: 30
together you are 50 years old

推荐阅读