python - 为什么尝试调用此模块会导致“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”错误。为什么?
解决方案
首先,sum是一个 python 内置函数,所以你应该将你的函数重命名为my_sum
还有两种方法可以导入函数
from totalages import my_sum
,它告诉解释器去查看totalages.py
并导入函数my_sum
,然后你可以直接使用my_sum(a, b)
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
推荐阅读
- excel - 有关运行时错误 9 的信息
- html - 如何使居中的 SVG 图像和文本响应?
- postgresql - 无法设置 cron 作业来备份 postgresql 数据库
- serenity-bdd - Serenity + Sauce Lab:如何修复身份验证错误
- angularjs - 我正在使用 angularJs 并在嵌套的 ng-repeat 中使用 ng-if。如何在 ng-if 中进行变量比较?
- scala - flink 增加异步操作的并行度
- keras - 处理 Bagging 方法时如何修复 TypeError: +: 'int' 和 'NoneType' 的不支持的操作数类型
- php - 对于某个 8 位图像 imagecolorallocate() 对大多数颜色返回 false
- javascript - Angular 6 - 使用子组件中的函数
- aws-sdk - 有没有办法使用 sdk 更新 api 键值?