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
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.
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.
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.