4\15 digit_sum : "'int' object is not iterable" error


#1

I have tried to solve this problem on my own text editor and it worked well on terminal.

however, the codecademy compiler showed me an announcement that I threw an error " "int" object is not iterable".

could you help me ? what wrong with these code line ?

def digit_sum(n):
total = 0
for i in n:
total = total + int(i)
return total

I have tried with :

def dg_sum(n):
c = []
tt = 0
for i in n:
c.append(i)
for e in c:
tt = tt + int(e)
return tt

and it got the same bug.

thanks you so much !


#2

Your error message is quite clear on what is going on, you are trying to iterate over an integer. In Python integers cannot be iterated over, you would have to convert it to a type or pass it to a function that would or could be iterated over.

Example:

a = 321
try:
    for i in a:
        print(i)
except TypeError:
    for i in range(a):
        if i % 31 == 0: print(i)
    for i in str(a):
        print(i)

Run this bit of code and you will see what does and does not run. That should explain what you have going on better.


#3

I'll try it, thank you so much


#4

you can't "surf" through integer, so try to convert to str and then you convert back to int,

heres how i did

def digit_sum(n):
    e = 0
    for i in str(n):
        e += int(i)
    return e

#5

it works also :smile:

def digit_sum(n):
n = str(n)
total = sum(map(int, n))
return total