Variables defined outside the function (i.e. global scope) can be referenced inside the function, but cannot be modified.
If you want to use an outer (global) variable in the function, if you use global to mark the variable inside the function, you can "read" the variable inside the function as much as possible; if you want to modify the global variable inside the function, you need to use the global statement, and the modification of the variable by the function will also be reflected in the global scope.
>>> oo=123 >>> def kai(): print(oo) oo = pp+1 print(oo) >>> kai() Traceback (most recent call last): File "<pyshell#91>", line 1, in <module> kai() File "<pyshell#90>", line 2, in kai print(oo) UnboundLocalError: local variable 'oo' referenced before assignment >>> def kai(): print(oo) #oo = pp+1 print(oo) >>> kai() 123 123 >>> oo+=1 >>> oo 124 >>> kai() 124 124 >>>
However, the global variables can be modified within the function by defining the function as follows
>>> def kai(): global oo print(oo) oo = oo+1 print(oo)
nonlocal specifies the variable name in the upper scope (but excluding the global scope) used in the current scope
nonlocal can only be used in functions within a function. If the statement is used directly in functions defined under the global scope, an error will be reported
>>> def yun(): nonlocal y #You can't write at all SyntaxError: no binding for nonlocal 'y' found
See an example of using nonlocal correctly
>>> n=1 >>> def outer(): n='n' print(n) def inner(): nonlocal n n='nn' print(n) inn() print(n) >>> outer() n #Print the n defined by the outer layer first nn #Inner function modifies variable n in outer function nn #Then the outer function prints n, which becomes the modified value of the inner function >>>
Let's take another example
>>> n=1 >>> def outer(): #print(n) n='n' print(n) def inner(): global n #Use global instead of the above example #nonlocal n n='nn' print(n) inner() print(n) >>> outer() n nn n #You can see that the n of the outer function has not been modified >>> n #The global variable n is modified by the inner function 'nn'
The rule here is only for immutable elements, such as string numbers, etc., which are invalid for variable elements such as list or queue typing. The underlying reason is that adding, deleting and modifying elements to a mutable object is not a modification of the object itself