Return a calculation
Provide a computed result from a function to its caller.
Python · Const
The return statement exits the current function call and provides its result. With no expression, it returns None; generator and asynchronous-generator functions have specialized completion rules.
Within a function, return ends the current call and supplies either the evaluated expression list or None when no expression is present. It also has special completion behavior for generator functions, and a finally clause runs before control actually leaves a try statement.
return [expression_list]| Name | Type | Description |
|---|---|---|
expression_list | expression list | Optional expression list whose evaluated result becomes the function's return value. |
The evaluated expression list, or None when the expression list is omitted.
def divide(total: float, count: int) -> float | None:
if count == 0:
return
return total / count
print(divide(10, 2))
print(divide(10, 0))The first call returns a calculated value; the second uses an empty return and therefore produces None.
Provide a computed result from a function to its caller.
Stop processing early after a condition is met.
Finish a generator and optionally attach a value to StopIteration.
return ends the current function call. With an expression list, that value is evaluated and returned; without one, the returned value is None.
Follow-up: What happens if return occurs in try with finally? The finally clause executes before the function is actually left.
In a generator, return marks the generator as finished and causes StopIteration. If it supplies a value, that value becomes the StopIteration.value attribute.
Follow-up: How does this differ for an asynchronous generator? An empty return raises StopAsyncIteration, while a value-returning return is a syntax error.
The statement has the form return [expression_list] and may occur syntactically nested in a function definition, but not within a nested class definition.
Follow-up: What does an omitted expression mean operationally? Python substitutes None as the return value.
yieldraiseStopIterationStopAsyncIterationtryfinally