CodeMIRAI
0 XP

Return values

2 min read 5 runnable examples Quiz included

So far our functions have printed things. More often, a function should give back a result so the rest of the program can use it. That's what return does.

Python
def square(n):
    return n * n

result = square(7)
print(result)
print(square(3) + square(4))

The call square(7) is replaced by the value it returns, so it can be stored, printed, or used in a bigger expression.

This is the most important distinction in this lesson:

Python
def add_print(a, b):
    print(a + b)

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

x = add_print(2, 3)     # shows 5, but x gets nothing back
y = add_return(2, 3)    # shows nothing, but y is 5
print("x =", x)
print("y =", y)

A function without a return gives back None. print shows a value to a person; return hands a value to your program.

return ends the function

As soon as Python reaches return, the function stops. This allows an early return:

Python
def check_age(age):
    if age < 0:
        return "That's not a valid age."
    if age < 18:
        return "Minor"
    return "Adult"

print(check_age(-3))
print(check_age(12))
print(check_age(40))

Early returns often replace deeply nested if/else blocks with something flatter and easier to read.

Returning a boolean

Functions that answer a yes/no question conventionally start with is_ or has_:

Python
def is_even(n):
    return n % 2 == 0

for n in range(1, 6):
    if is_even(n):
        print(n, "is even")

return n % 2 == 0 returns the comparison's result directly; there's no need for if ...: return True else: return False.

Returning several values

Return a tuple and unpack it:

Python
def stats(numbers):
    total = sum(numbers)
    return min(numbers), max(numbers), total / len(numbers)

low, high, average = stats([4, 8, 15, 16, 23, 42])
print(low, high, round(average, 2))
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.