Python provides the Global Variables
which are variables but can be accessed globally from the Python script. Variables have a scope that is used to access them. A regular variable can not be accessed outside of its scope. Global variables are defined as global and can be accessed from all scopes at the same Python script or module.
Local Variable
Let’s start with the local variable which is useful to understand the global variables. A local variable is defined inside a function where it can only use inside this function and can not be used outside of the function.
def calculate():
x =2
print(x)
calculate()
Global Variable
We can define global variables by putting them outside of the function. These global variables can be accessed inside the function. If a local variable with the same name as the global variable is created inside the function the local variable has precedence.
def calculate():
x = 2
print(x)
x = 4
calculate()
print(x)
2 4
Create Global Variable Inside Function
We can also create a global variable inside a function by using the global
keyword. The global keyword is used before the variable name like specifying the variable type. In the following example, we set the variable named x
as a global variable inside the function calculate()
and use this global variable in the global scope without any problem.
def calculate():
global x
x = 2
print(x)
calculate()
print(x)
2 2
Change Global Variable Value Inside Function
Another case about the global variables is changing a globally defined variable value inside a function. First, we create a variable in global scope without using the global
keyword. Then we create the same variable inside a function by using the global
keyword. Then we set a new value for the global variable which also affects the globally defined variable.
x = 4
def calculate():
global x
x = 2
calculate()
print(x)
2