Until now functions showed things with print. The most usual thing, however, is for a function to calculate a result and return it to whoever called it.
return
def add(a, b):
return a + b
result = add(3, 4)
print(result) # 7
print(add(10, 5) * 2) # 30
return ends the function and hands over the value, which you can store in a variable, show or use in another operation.
print versus return
def double_print(n):
print(n * 2) # only shows
def double_return(n):
return n * 2 # hands over the value
x = double_print(5) # shows 10
print(x) # None: it returned nothing
y = double_return(5) # shows nothing
print(y) # 10
A function without return returns None. A function that only calculates should use return and let the caller decide whether to show it, as in Function sum or Calculate double a number.
return ends the function
def sign(n):
if n > 0:
return "positive"
if n < 0:
return "negative"
return "zero"
print(sign(-3)) # negative
As soon as a return runs, the function ends; any code after it does not run.
Returning several values
Python lets you return several values separated by commas (actually, a tuple) and collect them in different variables:
def min_and_max(numbers):
return min(numbers), max(numbers)
low, high = min_and_max([4, 9, 1, 7])
print(low, high) # 1 9
It is the idea of Find the minimum and maximum in an array.
Returning booleans
Functions that answer a question are named with is_ and return True or False:
def is_even(n):
return n % 2 == 0
print(is_even(6)) # True
if is_even(7):
print("even")