Local and Global Variables
What are local variables?
Local variables are variables that are defined or declared inside of a function.
As such, they can only be called and used inside of the function. We say that the scope of a local variable is the function that it is defined in.
Let's take a look at an example:
def my_function():
a = 1
print(a)
This results in an error, as a
is defined inside of the my_function
.
However, the function my_function
has not been called, so the computer does not know what a
is.
We can fix this by first calling the function my_function
:
def my_function():
a = 1
my_function()
print(a)
This results in 1
being printed.
What are global variables?
Global variables, on the other hand, are defined or declared outside of the function.
They can be used anywhere in the code. We say that the scope of the variable is the entire script, accessible to any other function.
a = 1
def add_a_to_b(b):
print(a + b)
add_a_to_b(2) # prints 3
The function add_a_to_b
does not need to redefine a
as it already knows what it is.
It is a very good idea to use global variables sparingly, as they can be very dangerous. You usually don't need to maniuplate one variable accross multiple functions.
In general, you only want to limit your functions to only use local variables.