Digit_sum - when to use return and print?


#1



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


The first time i tried to do this question, i got the error message
"Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11."
After fiddling around, i figured out my problem lies with my use of "return" and "print".

My question is: when do you use "return" and "print" in a function, and why? The two methods below theoretically both work, however, the program only approved the second one.


def digit_sum(n):
    x=0
    for i in str(n):
        x += int(i)
    print x
digit_sum(434)

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


#2

You should return keyword if output of function could be use for something again. For example:

def cube(number):
    return number ** 3

some_var = 34 * cube(3)
print some_var

You can use print in functions which output can't be used anywhere else.

def hello(name):
    print "Hello " + name

hello("John")

print takes its arguments/expressions and dumps them to standard output, if you want to save output from a function to a variable, you should use return.