0
0
Pythonprogramming~5 mins

Multiple return values in Python

Choose your learning style9 modes available
Introduction

Sometimes a function needs to give back more than one piece of information. Multiple return values let a function send back several results at once.

When you want a function to give back both a result and some extra details, like a calculation and its steps.
When you need to return different types of data together, like a number and a message.
When you want to split a task into parts and return all parts at once.
When you want to return coordinates like x and y from a function.
When you want to return both success status and data from a function.
Syntax
Python
def function_name():
    # do something
    return value1, value2, value3
You separate the values you want to return with commas.
Python automatically packs these values into a tuple.
Examples
This function returns two values: a name and an age.
Python
def get_name_and_age():
    return "Alice", 30
Returns both the sum and product of two numbers.
Python
def calculate():
    sum = 5 + 3
    product = 5 * 3
    return sum, product
This function returns nothing explicitly, so it returns None.
Python
def no_return():
    print("Hello")
Sample Program

This program defines a function that returns two values: the quotient and remainder of dividing two numbers. Then it prints both values.

Python
def divide_and_remainder(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

q, r = divide_and_remainder(17, 5)
print(f"Quotient: {q}")
print(f"Remainder: {r}")
OutputSuccess
Important Notes

You can assign the returned values to separate variables like in the example.

If you only want some of the returned values, you can use an underscore (_) to ignore others.

Multiple return values are actually returned as a tuple behind the scenes.

Summary

Functions can return many values separated by commas.

Returned values are grouped as a tuple automatically.

You can easily capture these values into separate variables.