Digit_sum, need explanation


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


Oops, try again. Your function fails on digit_sum(434). It returns 4 when it should return 11.


hello, i'm new to programming and just learnt a few things.
i am stuck in this section and don't know why my code didn't work, can anybody explain it.


def digit_sum(n):
    total = 0
    a = abs(n)
    for word in str(a):
        b = int(word)
        total += b
        return total


#2

It's a problem of identation... The return should be at the same level as the for...
In python the indentation makes a big difference


#3

to add to @konaesan good answer, by default a function returns None at the end. If we want to return something different we can use the return keyword. But this means that the function ends the moment a return keyword is reached

If the return keyword is reached in a loop, the loop simply breaks. konaesan is right, you need to change the indent of return total, because the whole loop need to run, and indention determines what is listed inside the loop and what is not


#4

thank you. i didn't notice that. lol


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.