Return multiple values from a function
Introduction:
- In Python, you can return multiple values from a function using the
returnstatement. The values must be separated by commas.
Syntax:
python
def someFunction():
# some code
return a, b, c
- Replace
a,b, andcwith the values you want to return.
Example:
- Let's create a
swapfunction that takes two arguments, swaps their values, and returns both of them.
Python Program:
python
# Function that returns multiple values
def swap(x, y):
temp = x
x = y
y = temp
return x, y
# Take two values
a = 10
b = 20
print(f'\nBefore Swap - (a, b) : ({a}, {b})')
# Swap a, b
a, b = swap(a, b)
print(f'\nAfter Swap - (a, b) : ({a}, {b})')
Output:
Before Swap - (a, b) : (10, 20)
After Swap - (a, b) : (20, 10)
Explanation:
- The
swapfunction takes two arguments,xandy. - It swaps their values and returns both
xandy. - The returned values are then unpacked back into
aandb.
Exercises:
- Return Multiple Values from a Function:
Write a function
calculatethat takes two numbers and returns their sum, difference, and product.pythondef calculate(x, y): sum = x + y difference = x - y product = x * y return sum, difference, product # Test the function result = calculate(10, 5) print(result) # Output: (15, 5, 50)
- Return Tuple from a Function:
Write a function
get_student_detailsthat takes a student's name, age, and grade, and returns them as a tuple.pythondef get_student_details(name, age, grade): return name, age, grade # Test the function student = get_student_details("Alice", 14, "9th") print(student) # Output: ('Alice', 14, '9th')
- Unpack Multiple Return Values:
Write a function
split_namethat takes a full name and returns the first name and last name separately. Unpack the returned values into separate variables.pythondef split_name(full_name): first_name, last_name = full_name.split() return first_name, last_name # Test the function first, last = split_name("John Doe") print(f'First Name: {first}, Last Name: {last}') # Output: First Name: John, Last Name: Doe
Summary:
- In this tutorial, we learned how to return multiple values from a function using the
returnstatement. This allows you to get multiple results from functions and use them elsewhere in your program. Practice writing functions with multiple return values to become proficient in this essential programming concept!