Introduction To Return
Introduction To Return
In Python, the return statement is used within a function to exit the function and optionally pass a
value (or multiple values) back to the caller. When a return statement is encountered, the
function execution stops, and control is returned to the code that called the function. The value
following return (if any) is returned to the caller as the function’s result.
Syntax of return
return [expression]
expression is optional. If provided, this is the value that the function returns. If
omitted, the function returns None by default.
If you want, you can unpack these values into separate variables:
x, y = get_coordinates()
print(x) # Output: 5
print(y) # Output: 10
3. Returning Early from a Function:
You can use return to exit a function early, even before reaching the end of the
function’s body.
def check_positive(n):
if n <= 0:
return "Not positive"
return "Positive"
print(check_positive(10)) # Output: Positive
print(check_positive(-5)) # Output: Not positive
4. Returning None :
If a function does not explicitly return a value or if you use return without an
expression, Python returns None by default.
def do_nothing():
return
result = do_nothing()
print(result) # Output: None