Python global variables and global keywords

Python global variables

and the global keyword

in Python variable usage, this error is often encountered :

local variable 'a' referenced before assignment

means that the local variable “a” is referenced before assignment.
such as running the following code will cause this problem:

a = 3
def Fuc():
    print (a)
    a = a + 1
Fuc()

, but if you delete a = a + 1, the above problem will not occur.

a = 3
def Fuc():
    print (a)
Fuc()

it turns out that in Python, a = 3 defines the global variable a, scope to the end of the code from the definition, in a = 3 of the following functions can be cited the global variable a, but if you want to modify the functions and global variables with the same name, the function of the variable will become a local variable, before the change of the variable reference nature presents undistributed or undefined error.

if you are sure to reference and modify global variables you must add the global keyword

a = 3
def Fuc():
    global a
    print (a)
    a=a+1
Fuc()

note: which function needs to modify the global variable, just declare it in the function.

but there is a special function, and that is the main function:

a = 3
def Fuc():
    global a
    print (a)  # 1
    a = a + 1
if __name__ == "__main__":
    print (a)  # 2
    a = a + 1
    Fuc()
    print (a)  # 3

output is as follows (in Python3) :

3
4
5

three prints are executed in the order of 2, 1, 3. You can see that there is no global declared variable A in the main function, but you can still modify the global variable A. In a normal function, the global variable A needs to be declared globally in order to modify it.

life is short, I use Python~

Read More: