4. digit_sum


#1



The program lets me pass this exercise but I know my code is wrong. I tried it with the bill variable and its not printing 10 when the input is 1234. What am I doing wrong?


def digit_sum(n):
    string_n = str(n)
    total = 0
    for char in string_n:
        total = total + int(char)
    return total
    print total
    
bill = raw_input("Digit")
digit_sum(bill)


#2

Hi this part

return total
print total

you should put first the print statement then the return statement like that

print total
return total

#3

Ah that works. Thank you


#4

Hi, can someone help me understand why that code above works? I'm kinda lost...I just don't understand really what's going on especially what the bill and raw input stuff is or why it is there.
Thanks


#5

The whole bill thing was just a way for me to test the code.

I turned the variable to a string then looped through it to add each number. Tbh I'm still a little confused why it all works


#6

Could you please explain to me why this needs to be done in this order?


#7

HIin the function when you use the return statement every line after the return statement doesn't run, so that why you have to put the print statement before


#8

OK Thanks! :grinning: