One of the most powerful aspects of functions is their ability to 'return' values. This means a function can perform a calculation or process data, and then send the result back to the part of your program that called it. Think of it like ordering a pizza; you ask for it (call the function), and the pizza place makes it and gives it back to you (the return value).
To make a function return a value, you use the return keyword. Whatever expression, variable, or value comes after return will be sent back.
def add_numbers(x, y):
sum_result = x + y
return sum_result
result = add_numbers(5, 3)
print(result)In the example above, the add_numbers function calculates the sum of x and y. The return sum_result line sends that sum back. The line result = add_numbers(5, 3) captures this returned value and stores it in the result variable. Finally, print(result) displays the value that was returned.
What happens if a function doesn't have a return statement? By default, Python functions return None. This is a special value representing the absence of a value.
def greet(name):
print(f"Hello, {name}!")
return_value = greet("Alice")
print(return_value)In this greet function, print is executed, but there's no return statement. So, when we try to capture its return value, we get None.
A function can return multiple values. To do this, you simply separate the values you want to return with commas. Python will automatically pack these into a tuple.
def get_coordinates():
x = 10
y = 20
return x, y
coords = get_coordinates()
print(coords)
print(type(coords))When calling a function that returns multiple values, you can also 'unpack' them directly into separate variables, which is often more convenient.