4/15 digit_sum


def digit_sum(n):
summ = 0
for l in ln:
num = int(l)
summ += num
print summ
return summ
I've done the exercise by copying it from here but could someone please explain to me how it works please if you have
an answer please tell me, thank you for any replies


your code accepts the integer n but treats it as a string via
ln = str(n)

This means now you can traverse your string as a list (remember, the same can't be done with an integer, right?)

for l in ln:
num = int(l)
summ += num

Now above code does the traversal character by character in the string and in each step that character is again converted into integer via ** int(l)**, and added to the total sum.

My take was a bit different though, I treated the input as integer only (see below):

def digit_sum(n):
    sum = 0
    while(n > 0):
        sum += n%10
        n /= 10
    return sum


Thank you I understand now.


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