Creates or Updates a global variable from a nonglobal scope
Usage
The global keyword is used to create or update a global variable from a nonglobal scope (such as inside a function or a class).
Syntax
global var1,var2,…
| Parameter | Condition | Description |
| var1,var2,… | Required | List of identifiers you want to declare global |
Modifying Globals Inside a Function
A variable declared outside all functions has a GLOBAL SCOPE. It is accessible throughout the file, and also inside any file which imports that file.
x = 42 # global scope x
def myfunc():
print(x) # x is 42 inside def
myfunc()
print(x) # x is 42 outside defAlthough you can access global variables inside or outside of a function, you cannot modify it inside a function.
Here’s an example that tries to reassign a global variable inside a function.
x = 42 # global scope x
def myfunc():
x = 0
print(x) # local x is now 0
myfunc()
print(x) # global x is still 42Here, the value of global variable x didn’t change. Because Python created a new local variable named x; which disappears when the function ends, and has no effect on the global variable.
To access the global variable rather than the local one, you need to explicitly declare x global, using the global keyword.
x = 42 # global scope x
def myfunc():
global x # declare x global
x = 0
print(x) # global x is now 0
myfunc()
print(x) # global x is 0The x inside the function now refers to the x outside the function, so changing x inside the function changes the x outside it.
Here’s another example that tries to update a global variable inside a function.
x = 42 # global scope x
def myfunc():
x = x + 1 # raises UnboundLocalError
print(x)
myfunc()Here, Python assumes that x is a local variable, which means that you are reading it before defining it.
The solution, again, is to declare x global.
x = 42 # global scope x
def myfunc():
global x
x = x + 1 # global x is now 43
print(x)
myfunc()
print(x) # global x is 43There’s another way to update a global variable from a no-global scope – use globals() function.
Create Globals Inside a Function
When you declare a variable global, it is added to global scope, if not already present. For example, you can declare x global inside a function and access it outside the function.
def myfunc():
global x # x should now be global
x = 42
myfunc()
print(x) # x is 42