Digit sum



My function works in other compilers and even in this compiler I called it and it works, but I am still receiving the error that my code outputs 'None' instead of whatever number they want.

def digit_sum(n):
    convert = str(n)
    total = 0
    for i in convert:
        total += int(i)
    print total

This outputs 12 into the console window when I call it myself; however, the program is saying it outputs 'None'. Am I overlooking something or not doing it in the way they would like me to?


Well..first of all you need to return the total to nicely end the function.
If you want to print to the console, just do this:

print digit_sum(543)

Print the function call.


Thanks. Out of curiosity, is this python's way of making a private variable global?


It has nothing to do with making private variables global. It's just that return doesn't print to the console but it tells the function when to end and what to do once it ends. So that's why we have the print statement.

Global variables are ones that are outside the function and can be used inside a function. Such as

globalvar = 1 #a global variable

def random(): #random function
    global globalvar #using the global variable
    globalvar = 2 #changing the global variable

random() #calling to actually change the global variable
print globalvar #showing the global variable in the console

>> 2


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