What is the difference between global and local variables?
A variable inside a function is local to that function. Python forgets it when the function ends. A variable created outside any function is global, and every function can read it.
A global variable can be accessed anywhere in code. A local variable can only be used in a specific code block.
global variable example
We say the scope is global, it can be used in any function or location throughout the code.
In the example below we define a global variable, y amount lines of code later we can still use that variable.
x = 3
...
200 lines of code
...
print(x)
local variables
This is contrary to a local variable, which can only be accessed in the local scope.
In the example below, x is a local variable..
def f(x):
.. x can only be used here
If a variable is declared inside a function or loop, it’s a local variable. Global variables are usually defined at the top of the code.
best practice
Global variables are considered a bad practice because functions can have non-obvious behavior. Usually you want to keep functions small, staying within the size of the screen. If variables are declared everywhere throughout the code, it becomes less obvious to what the function does.
Why globals are risky
- A function that changes a global changes it for the whole program.
- Two functions that use the same global name fight over it.
- You have to read the whole file to know what a name means.
Pass values in as arguments and return the result instead:
def double(x):
return x * 2
That way the function is easy to test on its own.
If you really need a global, use global inside the function. For a
constant, put it in capitals at the top of the file.
Reading helps, writing fixes it. PyChallenge has exercises on this and you can try them right now.
