I pass the python codeacademy tutorial. task - to write a function that adds up the digits of a number and returns the result of the addition. my code is:

def digit_sum(n): n = str(n) summ = 0 for i in n: summ += int(i) print summ digit_sum(234) 

Result: 9, but an error pops up, saying that I have to return ( return ) the amount.

I change the code:

 def digit_sum(n): n = str(n) summ = 0 for i in n: summ += int(i) return summ digit_sum(234) print summ 

a message appears that the task is executed correctly, but the result is for some reason 15 ... at what, the result is 15 no matter what function argument I asked (whether 234, 32145 or 111) I can not understand what the problem is ...

    1 answer 1

    You do not store the value that digit_sum(234) returns

    At the end you need to write:

     print digit_sum(234) 

    Or:

     a = digit_sum(234) print a 

    The variable summ is a local variable of the function digit_sum(n) and cannot be accessed from outside in this way.

    • for sure. Thank you very much for the prompt response! :) but I still can not understand where the answer is coming from 15. - urri
    • I think 15 is some kind of internal interpreter variable on the codeacademy, if you execute this code in the system, you get NameError: name 'summ' is not defined - Alexander Loev
    • got it thanks again! - urri