Return Values

Understanding return values

In Python programming, a return value is the result that a function gives back, or ‘returns’, when it completes its operations. The keyword return is used, followed by the value or expression the function should pass back.

Note

If a function doesn’t explicitly return a value, it automatically returns None.

Syntax

1def function_name(parameters):
2    # code
3    return value_to_return

Here, value_to_return can be any data type: a number, a string, a list, or even another function.

Let’s look at an example where a function returns a value.

1def add(a, b):
2    return a + b
3
4result = add(5, 4);
5print(result)  # Output: 9

In this example, the function add takes two parameters, a and b, adds them together, and then uses the return keyword to give the sum back to the line of code that called the function. As you can see, the variable result stores the return value of the function.

Returning multiple values

Python allows a function to return multiple values. This is done by packing values into a tuple and returning this tuple.

1def calculate(a, b):
2    sum = a + b
3    difference = a - b
4    product = a * b
5    quotient = a / b
6    return sum, difference, product, quotient
7
8result = calculate(10, 2)
9print(result)  # Output: (12, 8, 20, 5.0)

In this example, the function calculate performs various calculations on the inputs a and b, and then returns the results as a tuple.

Note

When a function in Python returns multiple values, it actually returns a tuple, which can be unpacked into multiple variables.