Return values
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.
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.
print is not return
This is the most important distinction in this lesson:
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:
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_:
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:
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))