Coding

What Does Return Do in Python? The return Statement Explained

In Python, return ends a function and sends a value back to the code that called it. If you write return with no value, or never write it at all, the function gives back None.

Here is the smallest useful case:

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

total = add(2, 3)
print(total)

Example output:

5

The call add(2, 3) is replaced by the value 5, which is then stored in total. Without the return, total would hold None and the sum would be lost when the function finished.

What return does, step by step

The Python language reference defines it in two sentences. If an expression list is present, it is evaluated; otherwise None is substituted. Then return leaves the current function call with that value as the return value. Two things follow from this.

  1. The function stops at that line. Nothing after the return on that path runs.
  2. The value goes to the caller. The caller can assign it, print it, compare it, or use it as an argument to another function.

If you are new to calling functions, how to call a function in Python and JavaScript covers the other half of this: writing the call and passing arguments.

Code after return never runs

Because return exits immediately, you can use it as an early exit. This is often clearer than nesting everything inside an else:

def describe(number):
    if number < 0:
        return "negative"
    if number == 0:
        return "zero"
    return "positive"

print(describe(-4))
print(describe(0))
print(describe(9))

Example output:

negative
zero
positive

Each call reaches exactly one return. For -4, the first if matches and the function leaves right there, so the other two lines are never evaluated. A function can contain as many return statements as it needs, but every path through it should end in one, or in the implicit None described below.

Statements placed after a return that always runs are dead code:

def greet():
    return "hello"
    print("this line never runs")

The second line is unreachable, because the function leaves at return.

What a function returns without a return statement

The Python tutorial states that even functions without a return statement do return a value, "albeit a rather boring one": None. It also says that return without an expression returns None, and that falling off the end of a function does too. These three functions behave identically from the caller's point of view:

def a():
    pass

def b():
    return

def c():
    return None

print(a(), b(), c())

Example output:

None None None

One detail catches people in the interactive prompt. The interpreter suppresses a lone None, so calling a function that returns nothing appears to print nothing. The tutorial shows print(fib(0)) to reveal the None that was there all along.

print vs return

This is the confusion behind most searches for what return does. print shows text to a person. return gives a value to the program. A function that only prints cannot be used in a calculation:

def double_print(n):
    print(n * 2)

def double_return(n):
    return n * 2

x = double_print(4)
y = double_return(4)
print(x)
print(y + 1)

Example output:

8
None
9

The first 8 comes from the print inside double_print. Then x is None, because that function had no return. The value from double_return is a real number, so y + 1 works and gives 9. The Python tutorial makes the same point with its Fibonacci example: it is simple to write a function that returns a list of the numbers instead of printing them, and the returned list is more useful because the caller decides what to do with it.

The rule is general: if a function returns nothing, the variable you assign its result to will hold None.

Returning more than one value

List the values after return, separated by commas:

def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([7, 2, 9, 4])
print(low, high)
print(min_max([7, 2, 9, 4]))

Example output:

2 9
(2, 9)

This is not special syntax for multiple returns. The language reference says that an expression list containing at least one comma yields a tuple, so return a, b returns one tuple. The line low, high = ... then unpacks that tuple into two names. If you only want one of them, index the result: min_max(values)[0].

The same rule gives a trap with a trailing comma. return 5, returns the one-item tuple (5,), not the number 5.

return and try/finally

The reference says that when return passes control out of a try statement with a finally clause, the finally clause is executed before the function really leaves. That is why cleanup code still runs:

def read_first_line(path):
    handle = open(path)
    try:
        return handle.readline()
    finally:
        handle.close()

The line is read, the return value is prepared, handle.close() runs, and only then does the function exit. In real code, a with open(path) as handle: block does the same job more briefly.

return in generators

A function containing yield is a generator, and return means something different there. The reference says it indicates the generator is done and causes StopIteration to be raised. The returned value, if any, becomes the StopIteration.value attribute. A for loop over a generator handles this for you and simply ends, so you rarely see the value. In an asynchronous generator, a non-empty return is a syntax error.

Where return is allowed

The reference says return may only occur syntactically nested in a function definition, and not within a nested class definition. If you want to use return, put the code inside a function.

Returning a function call result: recursion

A function can return the result of calling another function, including itself. That is how recursion passes values back up the chain:

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))

Example output:

120

If the base case is missing, the calls never stop returning to themselves and Python raises an error, covered in RecursionError: maximum recursion depth exceeded.

If your function returns None unexpectedly

  • You printed instead of returning. Replace print(value) with return value, and print at the call site if you want to see it.
  • One branch has no return. If an if returns but the matching else case falls through, that case gives None. Check every path.
  • You returned inside a loop too early. A return in the first iteration ends the whole function, so the loop runs once. Put the return after the loop when you want a summary of all items.

Frequently asked questions

What does a Python function return if there is no return statement?
It returns None. The Python tutorial says that even functions without a return statement return a value, and that value is None. Falling off the end of the function body and writing a bare return both give the same result.
Can a Python function return more than one value?
Yes, by separating the values with commas, as in return width, height. Python builds a tuple from the comma-separated expression list, so the caller receives one tuple object that can be unpacked into separate variables: w, h = get_size().
What is the difference between print and return in Python?
print writes text to the screen and the function still returns None. return hands a value back to the code that called the function so it can be stored, compared or passed on, and it ends the function. Printing is output for people; returning is output for code.
Does code after return in a function still run?
No. return leaves the function immediately, so statements after it in the same path never execute. The one exception is a try statement with a finally clause: the finally block runs before the function actually exits.

Sources