Variables have a certain reach within a program. A global variable can be used anywhere in a program, but a local variable is known only in a certain area (function, loop)
Sometimes the word scope is used in projects: “its outside the scope of the project”, meaning not included. Likewise, a variable can be outside the scope of a function.
Related course: Python Crash Course: Master Python Programming!
Scope has to do with where a variable can be used. If you define a variable, it’s not necessarily usable everywhere in the code. A variable defined in a function is only known in a function, unless you return it.
That means unless you return the variables from a function, they can only be used there. This is in stark constrast with global variables: global variables can be used anywhere including in multiple functions and the main code. Global variables are often defined at the top of the program.
In the program below, balance is a global variable. It can be used anywhere in the code. But the variable x can only be used inside addAmount.
We have two variables: balance, a global variable that can be used anywhere. x, that can only be used inside the function (its not known outside, local scope).
Try the exercises below:
- Add a function reduce amount that changes the variable balance
- Create a function with a local variable