Codectionary / Developer documentation / Python

return

The return statement exits a function immediately and optionally sends a value back to the caller. A function can return any type - including multiple values as a tuple - or nothing at all, in which case it implicitly returns None. Once return executes, no further code in the function runs, making it useful for early exits as well as producing a final result.

Syntax

return value

Examples

Basic Return

Returning a single computed value from a function.

def square(n):
    return n ** 2

result = square(6)
print(result)  # 36

Returning Multiple Values

Python lets you return several values at once - they are automatically packed into a tuple.

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

low, high = get_min_max([4, 1, 9, 2, 7])
print(f"Min: {low}, Max: {high}")

Early Return

Using return to exit a function as soon as a condition is met, avoiding deeply nested code.

def get_discount(is_member, total):
    if not is_member:
        return 0  # exit early, no discount

    if total > 100:
        return 0.2

    return 0.1

print(get_discount(True, 150))  # 0.2
print(get_discount(False, 150))  # 0

Function Without Explicit Return

A function with no return statement implicitly returns None.

def log(message):
    print(f"LOG: {message}")
    # no return statement here

result = log("Server started")
print(result)  # None

Best practices

  • Use early returns to handle edge cases at the top of a function, keeping the main logic less deeply nested
  • Return multiple values as a tuple when they are closely related, rather than using a list or dictionary for just two or three values
  • Be consistent about what a function returns - avoid returning a value in some branches and None (implicitly) in others, as it can confuse callers
  • A function stops executing the moment return runs - any code written after it in the same branch is unreachable

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading