The return values of a function are a value that the function can return (optionally) as a result, after performing its operations.
Return values allow functions to perform calculations and operations, and then pass the result back to the code that called them.
If you want to learn more about Function Return
check the Introduction to Programming Course read more
Syntax of return
In Python, the return
statement is used to return a value from a function, to the point from where the function was called.
When the return
statement is encountered, the execution of the function stops and the value specified after return
is returned as the function’s result.
The basic syntax of return
is as follows:
def function_name(parameters):
# function code block
return value_to_return
Practical Examples
Returning a simple value
In its simplest form, return
is used to return a specific value from a function.
def add(a, b):
result = a + b
return result
# Calling the function and assigning the returned value to a variable
sum_result = add(5, 3)
print(sum_result) # Output: 8
Returning None
If a function does not have a return
statement or if return
is encountered without any value, the function implicitly returns None
.
def empty_function():
pass
result = empty_function()
print(result) # Output: None
Returning multiple values
Python only allows returning a single value in a return
. However, the returned type can be of any type, which includes groupings of variables.
We can use this to return multiple values from a function using return
, by returning a tuple, list, or any other data structure that contains the values to return.
def color_tuple():
return ("red", "green", "blue")
colors = color_tuple()
print(colors) # Output: ('red', 'green', 'blue')
Early exit from a function
return
can be used to exit a function early at any point. This is referred to as early return
.
This can be useful for checking conditions and returning a value without executing the rest of the function’s code. When used properly, it can improve code readability.
def check_negative_number(number):
if number < 0:
return "The number is negative"
else:
return "The number is positive or zero"
# Calling the function with different values
print(check_negative_number(-5)) # Output: The number is negative
print(check_negative_number(10)) # Output: The number is positive or zero
:::::::