Function return values 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, check out the Introduction to Programming Course
Return Syntax
In Python, the return statement is used to return a value from a function to the point from which 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
Return 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
Return 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
Return Multiple Values
Python only allows returning a single value in a return statement. 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 by returning a tuple, list, or any other type of data structure containing 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 called early return.
This can be useful for checking conditions and returning a value without executing the rest of the function’s code. When used well, 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
