So far you may have seen functions that print things directly. But printing is not always what you want — often a function should calculate a result and hand it back so the rest of your program can use it. This is what the return statement does.
The return Statement
def add(a, b):
return a + b
result = add(3, 7)
print(result) # 10
When Python reaches return, it immediately exits the function and sends the value back to wherever the function was called. Here, add(3, 7) evaluates to 10, which is stored in result.
A function that has no return statement (or just return with no value) automatically returns None. None is Python's way of representing "nothing". If you print a call to such a function, you will see None in the output.
Why Return Instead of Print?
Printing inside a function is a dead end — the value disappears after it is displayed. Returning a value keeps it available:
def square(n):
return n * n
s = square(5) # s = 25
total = square(3) + square(4) # 9 + 16 = 25
print(total) # 25
You can use the returned value in an expression, store it in a variable, pass it to another function, or put it in a list. You cannot do any of that with a printed value.
Returning Early
return also acts as an early exit. As soon as Python hits a return, the rest of the function body is skipped:
def classify(number):
if number > 0:
return "positive"
if number < 0:
return "negative"
return "zero"
print(classify(10)) # positive
print(classify(-3)) # negative
print(classify(0)) # zero
Each path through the function reaches exactly one return.
It is good practice to make sure every path through a function returns a value. Use an editor or linter to check for paths that might accidentally return None.
Returning Multiple Values
Python can return more than one value by separating them with commas. The result is a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
lowest, highest = min_max([4, 1, 9, 2, 7])
print(lowest, highest) # 1 9
Functions that return multiple things can be convenient, but too many return values makes the code confusing. If you find yourself returning five or more values, consider grouping them into a list or a dictionary instead.
Building Programs with Return Values
Return values let you chain functions together, where the output of one becomes the input of another:
def celsius_to_fahrenheit(c):
return (c * 9 / 5) + 32
def describe_temperature(f):
if f >= 100:
return "boiling"
elif f >= 30:
return "hot"
elif f >= 10:
return "mild"
else:
return "cold"
temp_c = 38
temp_f = celsius_to_fahrenheit(temp_c)
description = describe_temperature(temp_f)
print(f"{temp_c}°C is {description}.") # 38°C is hot.
Practice Problems
What is the difference between a function that prints a result and a function that returns a result?
Show answer
What does a function return if it has no return statement? How could this cause a bug?