When we write Python, we sometimes run into situations where we've already defined the variable n outside the function, printed it out inside the function, and then made the variable go up, and then ran into this error:
unboundlocalerror:local variable ' xxx ' referenced before assignment
As shown in the following code slice:
N=0
def func ():
print n
n+=1
func ()
This error occurs when the result is run.
This is because after you have modified the variable assignment inside the function, the variable is considered a local variable instead of a global variable by the Python interpreter, and when the program executes to N+=1, because the statement is assigned to n, so n becomes a local variable, then when you execute print N, Because n is not defined as a local variable, this error is thrown naturally.
Consider the following code slice:
N=0
def func ():
print n
func ()
Because the function does not have another value assigned to n, then print n prints the value of the global variable N.
So how do we get to the operation of printing and then assigning values inside a function? The conclusion is to use the Global keyword to declare that n is a global variable inside the function. The code is as follows:
N=0
def func ():
global n
print n
n+=1
func ()
print n
The results are as follows:
0
1
[finished in 1.0s]
At this point, N becomes a global variable, and there is no problem in modifying the variable inside the function.