How do you return values from a function in Python?
Returning Values from Python Functions: Single and Multiple Ways
Python uses the return statement to send values back from a function to the caller. In various ways, a function can return a single value or multiple values.
Returning a single value:
To return a single value from a function, we can simply use the return statement followed by the value you want to return.
Example: Returning a single value
def cube(num):
return num * num * num
result = cube(3)
print(result) # Output: 27
Returning multiple values using tuple:
We can return multiple values from a function as a tuple. The values should be separated by commas after the return statement.
Example: Returning multiple values using a tuple
def add_subtract_two_nums(x, y):
add_result = x + y
sub_result = x - y
return add_result, sub_result
result1, result2 = add_subtract_two_nums(25, 9)
print(result1) # Output: 34
print(result2) # Output: 16
Returning Multiple Values using a list:
Multiple values can also be returned as a list. Simply put the values in square brackets after the return statement.
Example: Returning multiple values using a list
def get_max_min_value(nums):
max_value = max(nums)
min_value = min(nums)
return [max_value, min_value]
result_list = get_max_min_value([3, 9, 12, 27, 8])
print(result_list) # Output: [27, 3]
Returning multiple values using a dictionary:
You can return multiple values as a dictionary by using the return statement along with a dictionary.
Example: Returning multiple values using a dictionary
def get_person_details(name, age, city):
info_dict = {"name": name, "age": age, "city": city}
return info_dict
result_dict = get_person_details("Zoe Osvaldo", 30, "London")
print(result_dict) # Output: {'name': 'Zoe Osvaldo', 'age': 30, 'city': 'London'}
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/python-interview/how-do-you-return-values-from-a-function-in-python.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics