digit_sum: Why doesn't my code work?



Can anyone tell me why this returns the wrong sum? It returns a huge number instead of the right one.

def digit_sum(n):
    a = str(n)
    b = []
    for i in a:
        abc = sum(list(b))
    return abc


Back this line out of the loop.


Its still not working now I've done that.


Turn b into an integer then add the a into it and convert the i variable back to an int while doing it as follows.

b = 0

b += int(i)

Then return the b for your grand total. Also mtf meant to say move the abc variable with its code back one indentation so it's no longer in the loop.


I worked it out! I also needed to change the n in the (int(n)) into an i. Can't believe I didn't see that!