int object is not iterable?

2020-01-29 05:33发布

inp = int(input("Enter a number:"))

for i in inp:
    n = n + i;
    print (n)

... throws an error: 'int' object is not iterable

I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?

Thanks

标签: python int loops
11条回答
你好瞎i
2楼-- · 2020-01-29 06:15

maybe you're trying to

for i in range(inp)

I just had this error because I wasn't using range()

查看更多
虎瘦雄心在
3楼-- · 2020-01-29 06:15

You can try to change for i in inp: into for i in range(1,inp): Iteration doesn't work with a single int. Instead, you need provide a range for it to run.

查看更多
孤傲高冷的网名
4楼-- · 2020-01-29 06:16

for .. in statements expect you to use a type that has an iterator defined. A simple int type does not have an iterator.

查看更多
小情绪 Triste *
5楼-- · 2020-01-29 06:18

Don't make it a int(), but make it a range() will solve this problem.

inp = range(input("Enter a number: "))
查看更多
劳资没心,怎么记你
6楼-- · 2020-01-29 06:21

try:

for i in str(inp):

That will iterate over the characters in the string representation. Once you have each character you can use it like a separate number.

查看更多
贼婆χ
7楼-- · 2020-01-29 06:24

Side note: if you want to get the sum of all digits, you can simply do

print sum(int(digit) for digit in raw_input('Enter a number:'))
查看更多
登录 后发表回答