The return values of a function are what the function returns as a result after performing its operations.
Return values allow functions to perform calculations and operations, and then provide the result back to the code that called them.
If you want to learn more
consult the Introduction to Programming Course read more
In Python, the return
statement is used to return a value from a function. This statement ends the function’s execution and returns the specified value, which can be used in the context where the function was called.
return
in Python
return
is a statement in Python that is used within a function to return a value to the point from where the function was called.
When the return
statement is encountered, the function’s execution stops and the value specified after return
is returned as the result of the function.
The basic syntax of return
is as follows:
def function_name(parameters):
# function code block
return value_to_return
Example of using return
Returning a simple value
In its simplest form, return
is used to return a specific value from a function.
For example,
def sum(a, b):
result = a + b
return result
# Function call and assignment of the returned value to a variable
sum_result = sum(5, 3)
print(sum_result) # Output: 8
Returning None
If a function does not have a return
statement or if it encounters return
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
. But, the returned type can be of any type, including variable groupings.
We can use this to return multiple values from a function using return
, by returning a tuple, list, or any other type of data structure containing the values to be returned.
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 called early return
This can be useful for checking conditions and returning a value without executing the rest of the function’s code. 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"
# Function call 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