Function Return Values - Lakelands Computing

Title
Go to content
Return - Getting data back from functions
As we said of the Parameters page, functions make blocks of code reusable but Python sees each Function as a stand alone "mini program".  This means two things:

1) Any data, such as variables and lists, you create outside of the function do not exist inside the function

2) Any data you create inside the function does not exist outside of the function.

To solve the first "problem" we have Parameters and Arguments. To solve the second one we have the return statement.

Here is a program that shows that the data doesn't work from inside a function, run it and you will see it errors on line 17 where it says it doesn't know what the variable answer is:
Here is the same program with the return statement in (line 5). Also note the change on line 15, There is now a variable , result, before the function call, addNumber(a,b). This result variable is needed to give the program somewhere to store the data being returned to it (I sometimes call it a catch variable when I'm explaining this as it "catches" the returning data - this is not a proper term though).

The result variable is then used again on line 18.
The statement is always:
  • return (dataToBeReturned)

This data can be a variable, a list, a dictionary etc. You can also have multiple pieces of data returned, eg - full example in the bottom trinket.

  • def function(a,b,c):
    • return (who,howOld,genders)

  • name, age, gender = function (x,y,z)

Really important Note : The order of the different pieces of data is really important:

Data from x goes into a and data from who is returned to name, which makes but if we changed it to:

  • def function(a,b,c):
    • return (genders,howOld,name)

  • name, age, gender = function (x,y,z)

Then the data in genders would be returned to the name variable. The computer sees strings of characters, it does not see words, and it certainly does not make decisions on what they are for based on the meaning of the words - that is your job.
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content