return does two things at once: it stops the function's execution immediately, skipping any remaining code in its body, and it hands a value back to wherever the function was called from. A function with no return statement, or a bare return with no value, implicitly returns None. You can return multiple values by returning a tuple, which the caller then typically unpacks into separate variables.
1Understanding return Statement
return does two things at once: it stops the function's execution immediately, skipping any remaining code in its body, and it hands a value back to wherever the function was called from. A function with no return statement, or a bare return with no value, implicitly returns None. You can return multiple values by returning a tuple, which the caller then typically unpacks into separate variables.
A bare return, with no value, inside a function is a valid, useful way to exit early — for example, in a guard clause that stops processing when some precondition isn't met — and it implicitly returns None just like falling off the end of the function would.
def square(x):
return x * x
result = square(5)
print(result)2Practical Example
Here is a real-world application of return Statement showing how it is used in production Python code.
def divide(a, b):
if b == 0:
return None
return a / b
print(divide(10, 2))
print(divide(10, 0))3Best Practices
Follow these guidelines when working with return Statement:
1. Use an early return as a guard clause to exit a function as soon as its precondition fails, instead of nesting the rest of the logic in an else block
2. Return a tuple to hand back multiple related values from a single function, rather than a custom container class
3. Keep a function's return type consistent across all its code paths, so callers don't have to guard against sometimes getting None and sometimes getting a real value unexpectedly
Tip: A bare return, with no value, inside a function is a valid, useful way to exit early — for example, in a guard clause that stops processing when some precondition isn't met — and it implicitly returns None just like falling off the end of the function would.
def square(x):
return x * x
result = square(5)
print(result)