Consider a python program like this:
x = 12
def func ():
x = 1
Func ()
Print (x)
Output is: x = 12
Because the x defined inside the function is considered to belong to the local scope only, in order to show that I am referring to the global x instead of the new definition of a local x,
You can use the Global keyword:
x = 12
def func ();
Global X
x = 1
Func ()
Print (x)
You can see that the output has become 1, which means that a global variable has been successfully modified inside the function.
Another scenario is the problem of nested local scopes:
def g ():
x = 12
Func ():
x = 1
Func ()
Print (x)
G ()
The result of this output is 12 because the x defined at the Func function call is also considered to belong to the local scope only, but the x defined in the function g () is not a global variable, and the global keyword mentioned above is certainly not possible,
So there is the nonlocal, so write:
def g ():
x = 12
Func ():
nonlocal x
x = 1
Func ()
Print (x)
G ()
At this point, the result of the output is our expected 1, nonlocal is to declare a variable to refer to an external scope (except the global scope) defined.
It is important to note that the above keywords are needed because we are trying to modify global variables or variables that are in an external scope, and if you redefine global variables or external scope variables inside local scopes, just read-only access (such as print out) is perfectly fine, see this example:
A = 12
def g ():
b = 11
def func ():
Print (a)
Print (b)
Func ()
Return
if __name__ = = ' __main__ ':
G ()
Python3 nonlocal vs Global