4.2 Returns

Getting to Know Functions

One of the core responsibilities of functions is to output information based on the input. We call these returns. To dedicate what information is returned, we use the return keyword. Anything after the return keyword in a function block is considered unreachable code. The Python interpreter simply stops reading a function after the return statement.

def new_f():
    return "I am a function"
print(new_f())
I am a function

The above function simply returns the string “I am a function.” The Python interpreter always evaluates the statement before continuing. Our print statement prints the return of new_f().

We can take advantage of this functionality to store the output of a function in a new variable.

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


x = 10
y = 11

z = add_numbers(x, y)
print(f"z now stores the product of x and y: {z}")
z now stores the product of x and y: 21

In fact, we can actually pass in the output of another function as a parameter for a function.

def multiply_nums(a, b):
    return a * b


x = 2
new_result = multiply_nums(add_numbers(1, 2), x)
print(new_result)
6

This is an atypical way of programming. In fact, I would recommend you never do this, but it indicates that it is possible because functions are always evaluated to their return before continuing.