Syllabus Lesson 21 of 239 · Functions
Functions

Return vs Print

This is the single most important habit for writing good functions, so go slow here.

print() shows text on the screen for a human to read. return hands a value back to the code that called the function, so the program can keep using it. They are not the same thing.

def doubled_print(n):
    print(n * 2)        # shows it, hands back nothing

def doubled_return(n):
    return n * 2        # hands the value back

x = doubled_print(5)    # screen shows 10
print(x)                # prints None  (nothing was returned!)

y = doubled_return(5)   # nothing shown yet
print(y)                # prints 10  (we got the value back)

See the trap? doubled_print looks like it works, but x is None, so you cannot do math with it. A function that only prints is a dead end: you can read the answer but you cannot reuse it.

Rule of thumb: functions should return their result. Let the caller decide whether to print it, add to it, or save it. Returned values can be combined:

def add(a, b):
    return a + b

total = add(add(1, 2), add(3, 4))   # 3 + 7
print(total)   # 10

If you had used print inside add instead of return, that last line would be impossible.

Your turn

Define a function square that takes one parameter n and returns n * n. Do NOT print inside the function. The hidden tests check the returned value, so a function that only prints will fail.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output