Digit_sum: Code returns "none" twice after answer. Why?


#1

Wrote this code for def digit_sum:

 def digit_sum(n):
     numbs = []
     n=str(n)
     for i in n:
         numbs.append((int(i)))
     print sum(numbs)    

 print digit_sum(123)

the code as is returns:

6
None
None

Why is it doing that?


#2

Printing and returning are two different things.

Printing makes something show up on the screen.

Returning is when a function exits and it sends a value back to the caller.

Your function does not return anything. It prints.

You print the result of a function that does not return anything, hence None

The other None is not from your code, that's codecademy's environment, ignore the last None.


#3

I see, thank you.

So I always want the loops to return something to end them, even if i have multiple nested loops? But i have a for loop with if/else statements, I want the if/else statements to print, but the for to return? Is that correct?


#4

That is not what @ionatan is suggesting. He is only explaining why none appears. Your code is fine, as it is. However, if you are getting an error message from the SCT something like this:

your code returns none when it should return ...

that is a clue to what is expected... A return value, which means your code should return something from the method:

def digit_sum(n):
    numbs = []
    n=str(n)
    for i in n:
        numbs.append((int(i)))
    return sum(numbs)    

 print digit_sum(123)

Now the output will read,

6
none

The none is the return value of print and can be ignored.


#7