Classification scope
1, the global scope
Global can call the names present in the global scope
Built-in namespace + global name space
2, local scope
Local can call the name stored in the local scope
The local name space
3、 global
Declare global variables
4、 nonlocal
Local namespace declarations local variables, modify variables in the upper function of local
Only a variable-type value can be changed in the local external variables
x = 1
def index():
global x
x = 2
index()
print(x)
# 在局部修改外部函数的变量
x = 1111
def index():
x = 1
def func2():
x = 2
def func():
nonlocal x
x = 3
func()
print(x)
func2()
print(x)
index()
print(x)
# 只有可变类型可以在局部修改外部变量的值
l1 = []
def index(a):
l1.append(a)
index(1)
# 局部变量的修改无法影响上层,上上层
def index():
x = 1
def index2():
nonlocal x
x = 2
index2()
print(x)
index()