Python Reference ยท Statements and Keywords
The return statement
Reference for Python's return statement: return one or many values, implicit None, early exits, returning tuples, finally blocks and common mistakes.
return ends the execution of the current function and hands a value back to the caller. If there is no return, or a bare return with no value, the function returns None.
Python has no separate "multiple return values" feature: return a, b builds a single tuple, which the caller usually unpacks. In a generator, return stops iteration and its value travels in StopIteration.
def divide(a, b): if b == 0: return None return a / b
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
return return expression return expression, expression # returns a tuple return *items, last # unpacking in the value (3.8+)
| Form | Result |
|---|---|
return |
None |
return x |
The value of x |
return a, b |
The tuple (a, b) |
no return |
None, when execution runs off the end of the body |
Raises: SyntaxError if used outside a function (at class or module level).
Usage notes
- Forgetting
returnis a classic bug: the function computes a value and quietly returnsNone, which then fails later with a confusingTypeErrororAttributeError. Methods that mutate in place (list.sort(),list.append()) deliberately returnNone. - Be consistent. Either return a value on every path or on none. Mixed
return xand implicitNoneis allowed but easy to get wrong. finallywins. Thefinallyblock runs before the function exits, and areturninsidefinallywould replace the original return value and swallow exceptions; avoid it (Python 3.14 warns about this).- Several values are one tuple. Use a
NamedTupleor dataclass when there are more than two or three, so callers have names instead of positions. - Returned objects are not copied. Returning an internal list lets callers change your state.
- Early returns (guard clauses) usually read better than deeply nested
if/elseblocks. - Lambdas and generators. A lambda returns the value of its expression with no
returnkeyword. In a generator,return valuesetsStopIteration.value, whichyield frompasses on as its result. - In async functions,
returnproduces the value thatawaitgives to the caller.
Related
def,lambda,yield,tryStopIteration, generators and iterators- Lessons: Return values, Functions