return

Ends a function and returns a value to the place it was called from.

On this page

Example

#
Python
def min_max(values):
    return min(values), max(values)

low, high = min_max([72, 95, 64, 88])
print(low, high)

def greet(name):
    print(f"Hi, {name}!")

result = greet("Emma")
print(result)
Resultsaved result, you can check it
64 95
Hi, Emma!
None

Definition and usage

#

The return statement ends a function’s execution and passes the result back to where the function was called. Code after return in the same block no longer runs.

A function with no return (or with a bare return) returns None. This is a common source of bugs: the result of a function that only prints something is not usable in further calculations.

You can return several values at once, separated by commas. Python packs them into a tuple, which you can conveniently unpack at the call site: low, high = min_max(values).

Syntax

#
Syntax
def name():
    return value

Good practices

#
  • An early return for special cases (empty data, invalid arguments) simplifies the rest of the function.
  • Remember that a function which prints its result with print() does not return it. You need return to use the value further.

Related entries

#

Spotted a mistake or missing an example? Write to us.