In Python, function return values are a crucial concept that allows functions to send data back to the caller. They provide a way for functions to communicate results and share information with other parts of your program.
When a function completes its execution, it can send a value back using the return
statement. This value can be of any data type, including numbers, strings, lists, or even other functions.
def function_name():
# Function body
return value
The return
statement immediately exits the function and passes the specified value back to the caller.
def square(number):
return number ** 2
result = square(5)
print(result) # Output: 25
In this example, the square
function returns the square of the input number.
def calculate_stats(numbers):
return sum(numbers), len(numbers), sum(numbers) / len(numbers)
total, count, average = calculate_stats([1, 2, 3, 4, 5])
print(f"Total: {total}, Count: {count}, Average: {average}")
# Output: Total: 15, Count: 5, Average: 3.0
Python allows functions to return multiple values as a tuple, which can be unpacked into separate variables.
return
statement implicitly return None
.return
without a value to exit a function early.To further enhance your understanding of Python functions, explore these related topics:
Mastering function return values is essential for writing efficient and modular Python code. Practice using different return types and multiple return values to become proficient in this fundamental concept.