There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.
Python Programming Bootcamp: Go from zero to hero
Local variables can only be reached in their scope.
The example below has two local variables: x and y.
The variables x and y can only be used inside the function sum, they don’t exist outside of the function.
Local variables cannot be used outside of their scope, this line will not work:
A global variable can be used anywhere in the code.
In the example below we define a global variable z
The global variable z can be used all throughout the program, inside functions or outside.
A global variable can modified inside a function and change for the entire program:
After calling afunction(), the global variable is changed for the entire program.
Local and global variables can be used together in the same program.
Try to determine the output of this program:
If you are new to Python programming, I highly recommend this book.