Add Return Values to Functions
In contrast to the previous step, most functions are designed to compute a value and return it to the caller. This is achieved using the return keyword. A return statement immediately exits the function and sends a specified value back.
Open the file return_function.py from the file explorer in your WebIDE.
Add the following code to define a function that adds two numbers and returns their sum:
def add_numbers(a, b):
"""This function adds two numbers and returns the sum."""
sum_result = a + b
return sum_result
## Call the function and store the returned value
total = add_numbers(5, 3)
## Print the returned value
print(f"The sum is: {total}")
## Use the returned value in another operation
another_total = add_numbers(10, 20) * 2
print(f"Another calculated value: {another_total}")
Save the file and run the script from the terminal:
python ~/project/return_function.py
You should see the following output, showing that the returned values were successfully captured and used:
The sum is: 8
Another calculated value: 60
A function can return any Python object, including numbers, strings, lists, and even tuples. Returning a tuple is a common way to return multiple values at once.
Add the following code to the end of your return_function.py file to see this in action:
def get_user_info():
"""This function returns user information as a tuple."""
name = "labex"
age = 25
city = "Virtual City"
return name, age, city
## Call the function and unpack the returned tuple into separate variables
user_name, user_age, user_city = get_user_info()
## Print the unpacked values
print(f"Name: {user_name}, Age: {user_age}, City: {user_city}")
Save the file and run it again:
python ~/project/return_function.py
The complete output will now be:
The sum is: 8
Another calculated value: 60
Name: labex, Age: 25, City: Virtual City
Here, get_user_info() returns three values packaged as a tuple. The calling code then unpacks this tuple into three separate variables, making it easy to work with multiple return values.