Function Parameters - Lakelands Computing

Title
Go to content
Parameters - Passing data into Functions
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.

This can be very desirable as it keeps variables and data organised and contained to the part of the program where it is needed, but it can appear to be a problem when you need data to move between functions.

To solve the first point we have Parameters and Arguments. To solve the second one we have return values

Lets's look at an example without parameters

def over18Check():
  • if age >= 18:
    • print ("You may enter")
  • else
    • print ("You are too young, sorry")

  • print ("please enter your age")
  • userAge = input()
  • userAge = int(userAge)
  • over18Check()

This will error as the age variable does not exist inside function. Try it in the trinket and see the error.
Now lets see how it should be

def function over18Check(userAge):
  • if age >= 18:
    • print ("You may enter")
  • else
    • print ("You are too young, sorry")

  • print ("please enter your age")
  • userAge = input()
  • userAge = int(age)
  • over18Check(userAge)

This will now work. The words in green are the parameter.

By adding the first one in the def function over18Check(userAge): statement, you are telling the function to expect a piece of data (an argument) and to store it in something called userAge.

The one in the call statement over18Check(userAge) is passing the piece of data, the argument, into the function.
Note - The parameter is the name of data being passed, eg userAge, the argument is the data that is in the parameter, eg. 19.

Parameters and arguments get the data into a function. To get it back out you need to use return values.
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