Since functions are like programs inside of a program, variables that are defined inside of functions do not exist for the rest of the program unless you tell it to. So for functions there are two types of variables:
Local Variables are made by:
Global Variables can be made in two ways:
Program Organization (Yes, you can lose marks for this if specified on future assessments)
1. Define all constants and global variables at the TOP of your program. That way it's easy to find what they are. Remember that variables don't have to just be integers, they can be lists, dictionaries, tuples, strings, floats, etc.
2. Most programmers don't have a #main, but use a function called main() instead. This is really the same as we have been doing but you put everything in a function called main() and then you call it out after you have defined all functions in your program. For the sake of this course, you can do it either way.
Making something Global
You might get an error that says this with reference to a variable (let's call it x in this case):
UnboundLocalError: local variable 'x' referenced before assignment
This is caused by a variable being re-defined inside of a function which causes it to become local.
To make the variable global again you have to type the line:
global x
Where x is the variable you need to be global.
Referenced Before Declaration Error/Warning
If you have a = 5 in #main and in a function you try to code:
You'll get an error/warning that says "Referenced before declaration".
To fix this, just use this code:
Try this example below.
Variable a is defined in #main.
Function x takes in variable a and adds 10 to it.
But Function x also creates a global variable y which is 5.
Back in main, after function x is called, you can see that global variable y is now valid in main.