Getting Results Back: return

print vs return

So far our functions print things. But often you want the function to give back an answer so you can use it. That's what return does.

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

result = add(3, 4)
print(result)
print(add(10, 20) * 2)

Output

7
60

Think of it like this: Asking a friend to calculate something. print is them shouting the answer across the room. return is them writing it on a note and handing it to you, so you can use it.

Using returned values

def area_of_circle(radius):
    return 3.14159 * radius * radius

def describe(radius):
    area = area_of_circle(radius)
    return f"A circle of radius {radius} has area {area:.1f}"

print(describe(2))
print(describe(10))

Output

A circle of radius 2 has area 12.6
A circle of radius 10 has area 314.2

return ends the function

As soon as Python reaches return, the function stops. This is useful with if:

def check_age(age):
    if age < 0:
        return "Invalid age"
    if age < 18:
        return "Minor"
    return "Adult"

print(check_age(-5))
print(check_age(12))
print(check_age(30))

Output

Invalid age
Minor
Adult

Returning True or False

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

print(is_even(10))
print(is_even(7))

Output

True
False

Common mistake: A function without return gives back None. If you see None printed unexpectedly, you probably used print inside the function where you meant return.

HOME LEARN COMMUNITY DASHBOARD