不明白为什么我得到一个'int'对象不是可迭代的错误

时间:2019-08-06 17:45:28

标签: python

不知道为什么我遇到TypeError:'int'对象不可迭代

first_age = int(input("Enter your age: "))
second_age = int(input("Enter your age: "))
total = sum(first_age, second_age)
print("Together you're {} years old".format(total))
Enter your age: 1
Enter your age: 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-6375ca82c6eb> in <module>
      4 second_age = int(input("Enter your age: "))
      5 
----> 6 total = sum(first_age, second_age)
      7 
      8 print("Together you're {} years old".format(total))

TypeError: 'int' object is not iterable

TypeError                                 Traceback (most recent call last)
<ipython-input-25-6375ca82c6eb> in <module>
      4 second_age = int(input("Enter your age: "))
      5 
----> 6 total = sum(first_age, second_age)
      7 
      8 print("Together you're {} years old".format(total))

TypeError: 'int' object is not iterable

3 个答案:

答案 0 :(得分:2)

sum仅可与可迭代对象一起使用。参见官方doc

语法本身是

sum(iterable[, start])

如果只需要对两个整数求和,请使用+运算符,如下面的代码所示。

sum = first_age + second_age 

答案 1 :(得分:2)

函数sum()用于累加可迭代次数。因此,如果输入sum([7,8]),将返回15。这就是为什么出现错误的原因,因为它试图遍历整数类型而不是数组。

修复如下:

first_age = int(input("Enter your age: "))
second_age = int(input("Enter your age: "))
total = sum([first_age,second_age])
print(f"Together you're {total} years old.")

答案 2 :(得分:1)

您不想使用sum

根据文档:

 sum(iterable[, start])
  

总和从左到右开始,并迭代一个项目,并返回总计。 start默认为0。可迭代项通常为数字,并且起始值不允许为字符串。

您只想使用加法。

first_age = int(input("Enter your age: "))
second_age = int(input("Enter your age: "))
total = first_age + second_age
print("Together you're {} years old".format(total))