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


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:
for e in c:
tt = tt + int(e)
return tt

and it got the same bug.

thanks you so much !


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.


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

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


I'll try it, thank you so much


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


it works also :smile:

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