<span style= "FONT-SIZE:18PX;" ></span><pre name= "code" class= "python" >y,z = 1,2
def change ():
y = y+2
z = z+2 retrun
y, Z
This code is to change the value of the global variable y,z, it seems that there is no problem, Y,z declared outside the function, the actual operation will be reported unbondlocalerror wrong.
This is because of the Python variable name resolution principle: the LEGB principle. When you use a variable name that is not authenticated in a function, Python searches for 4 scopes [local scope (L), followed by the local scope (E) of def or lambda in the previous layer structure, followed by global scope (G), and finally built-in scope (B)], And stop at the first place where you can find the variable name.
When assigning the variable name ' y ' to ' y+2 ', Python first finds the definition of y in the global variable by looking for y in the ' y+2 ' within the function (that is, the local variable). When Python first looks for the local variable, it finds the variable name y, but y doesn't define it, so even if we define the global variable Y, we still have an error. There are several ways to modify this to avoid this error.
(1) declaring the y,z as a global variable
<span style= "FONT-SIZE:18PX;" >y,z = 1,2
def change ():
global y,z #加入这一行
y = y+2
z = z+2
retrun y,z</span>
So there won't be any more errors, when the value is assigned, Python finds the variable name y, but y is a global variable, not a local variable, so Python does not find the definition of Y in the function, so it looks for y from the global variable, which gives us the results we want.
(2) Put the definition of y,z in the function
def change ():
y,z = 1,2
y = y+2
z = z+2
retrun y,z
Python finds the definition of y,z within a function, and there is no error. But it doesn't change the value of the y,z, and when the function is finished, the Y,z object does not exist.