The error I get is:
Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11.

So I assuming my code breaks down the string but only adds up the first i to total.

What I don't understand is why it only adds up the first i when I have it in a for.

The way I understand it is that when you write it as a for it should go through all the i's?

If anyone could clearify for my why this isn't working I would be greatful :slight_smile:

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


Hi @digitaljumper74537,

This should come before the loop ...

    total = 0

This should be after the loop, but it is indented to a degree that makes it part of the loop ...

    return total


NICE! So my code was actually not all that bad. After moving total to before the loop and the return to after, my code worked. Can you explain to me why it is important that the total comes outside of the loop?


This needs to be placed before the loop so that total starts out at 0 before the value of any of the digits gets added to it ...

    total = 0

Furthermore, if that statement is placed within the loop, total gets repeatedly set back to 0 each time the loop iterates, and what has previously been added to total gets lost.


Makes sense. Thank you