Week 8: Functions - The Power of Reusability
Learn how to define and use functions to write more organized and efficient Python code.
Explore Chapter 8Returning Values from Functions.
The `return` statement is used to send a value back from the function to the caller. A function can return any data type (e.g., a number, a string, a list, a tuple, a dictionary, or even another function).
Basic Return
def add(x, y):
return x + y
result = add(5, 3) # result will be 8
print(result)
Returning Multiple Values
Python functions can effectively return multiple values by returning them as a tuple.
def calculate_area_and_perimeter(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter
area, perimeter = calculate_area_and_perimeter(10, 5)
print("Area:", area)
print("Perimeter:", perimeter)
`None` Return
If a function does not explicitly include a `return` statement, or if the `return` statement is used without any value, the function implicitly returns `None`. `None` is a special value in Python that represents the absence of a value.
def print_message(message):
print(message)
return_value = print_message("Hello!")
print("Return value:", return_value) # Output: Return value: None