Global Variables in Python
In Python, variables defined outside any function are classified as global variables.
A global variable is accessible from any part of a program.
Conversely, variables declared within a function are local variables and can only be accessed within their respective function.
Take the variable x, for example; it is a global variable because it exists outside any function definitions.
x = "ok"
def func()
print(x)
func()
As such, it can be accessed by the func() function.
The output of this script will be:
ok
If a function defines a local variable with the same name as a global variable, it won't impact the value of the global variable.
x = "yes"
def func()
x = "no"
func()
print(x)
Here, the local variable x = "no" is confined to the function's scope.
The output from the function will be:
yes
To modify a global variable from within a function, it must be explicitly declared as global using the 'global' keyword.
x = "yes"
def func()
global x
x = "no"
func()
print(x)
This change will cause the function to replace the global variable’s value.
In this scenario, the function's output is:
no
It's also possible to create a new global variable within a function by declaring it global.
def func()
global y
y = "yes"
func()
print(y)
Consequently, the output from the function is:
yes