在Python程序中键入错误,'int'对象不可订阅'

时间:2016-03-13 17:48:23

标签: python

问题是'TypeError:'int'对象不可订阅',对于我完美的方程序,这里是程序出错的地方:

tested_number = input('What number do you want to test, maximum is 10000? ')    
y = 0   
sum_of_number = sum(int(y) for y in tested_number)#the sum of all the number in the list, highest is 36 due to 10000 limit
digital_root = sum_of_number[0] + sum_of_number[1]
if digital_root == (2, 3, 5, 6, 8, 9):
    print(tested_number, 'is not a perfect square')
    pass
print(tested_number, 'is a perfect square')

3 个答案:

答案 0 :(得分:0)

当你说:

for y in tested_number

您正在尝试迭代分配给tested_number的整数。你不能这样做。我不确定您打算将哪个变量作为列表,但ytested_number都不是列表。

答案 1 :(得分:0)

当我运行你的程序时,我得到了

$ python3 b.py
What number do you want to test, maximum is 10000? 456
Traceback (most recent call last):
  File "b.py", line 4, in <module>
    digital_root = sum_of_number[0] + sum_of_number[1]
TypeError: 'int' object is not subscriptable

在您的问题中显示完整的回溯非常有用,因为我们都可以确切地看到哪条线路出现故障。看看你的代码

sum_of_number = sum(int(y) for y in tested_number)#the sum of all the number in the list, highest is 36 due to 10000 limit

它非常直接。 sum_of_numberint(这是您期望的数字总和),int无法下标。

答案 2 :(得分:0)

在范围内求和

如果您希望将范围总和到测试编号,请尝试以下操作:

tested_number = input('What number do you want to test, maximum is 10000? ')    
sum_of_number = sum(y for y in range(tested_number))
print sum_of_number
What number do you want to test, maximum is 10000? 20
190