Python functions can return multiple variables. These variables can be stored in variables directly. A function is not required to return a variable, it can return zero, one, two or more variables.
This is a unique property of Python, other programming languages such as C++ or Java do not support this by default.
Related course: Complete Python Programming Course & Exercises
Variables defined in a function are only known in the function. That’s because of the scope of the variable. In general that’s not a problem, unless you want to use the function output in your program.
In that case you can return variables from a function. In the most simple case you can return a single variable:
Call the function with complexfunction(2,3) and its output can be used or saved.
But what if you have multiple variables in a function that you want access to?
Create a function getPerson(). As you already know a function can return a single variable, but it can also return multiple variables.
We’ll store all of these variables directly from the function call.
name = "Leona"
age = 35
country = "UK"
name,age,country = getPerson()
This will output:
Try the exercises below:
- Create a function that returns a,b and a+b
- Create a function that returns 5 variables
After completing these continue with the next exercise.