1. The upper function cannot directly use the variables of its nested function;
def func1 (x, y): = x + y def Func2 (): = 3 + = mreturn Zprint (Func1 (1, 2))# error: Name ' m ' is not defined
2. Variables in the upper function can be used directly within their nested functions:
def func1 (x, y): = x + y def Func2 (): = 3 + z return m return func2 ()print(func1 (1, 2))# output: 6
3. In nested functions, the upper function variable cannot be used, and its own variable has the same name as the upper layer variable:
def func1 (x, y): = x + y def Func2 (): # m=3 + z:z is the upper function variable m = 3 + z # z=m * * 2:z is a variable of the FUNC2 () function itself z = m * * 2 return zreturn Func2 ()print(func1 (1, 2))# error: local variable ' z ' referenced before assignment
# declare the variable in advance to be a non-local variable (the system automatically looks for the variable from the upper function): nonlocal Z
# Variables in code z are all variables of the func1 () function
4. The formal parameter of the upper function (x, y) can be used directly in its nested function;
def func1 (x, y): def Func2 (): = 3 + x = m + y return z return func2 () Print (Func1 (1, 2)) # Output: 6
5. The formal parameter of the upper function (x, y) can be the formal parameter of its nested function: The name of the formal parameter must be the same
def func1 (x, y): def Func2 (x, y): = 3 + x = m + y return z return func2 (x, y) C15>print(func1 (1, 2))# output: 6
Python: Use of function variables