#作用域if True: x = 3 #if没有作用域print(x)def f(): a = 3 #a这个变量属于函数 出了这个函数就没用了f()print(a)
#嵌套作用域 1x =1 def s(): global x #global 关键字可以修改全局变量 x = x + 3 #局部要修改全局变量需要添加global def sf(): # nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = 5 def sd(): nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = x + 7 print("3:",x) sd() print("2:",x) sf() print("1:",x)s()打印
3: 12
2: 12
1: 4
#嵌套作用域 2def s(): x = 3 def sf(): nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = 5 def sd(): nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = x + 7 print("3:",x) sd() print("2:",x) sf() print("1:",x)s()打印
3: 12
2: 12
1: 12
#嵌套作用域 3def s(): x = 3 def sf(): # nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = 5 def sd(): nonlocal x #nonlocal 关键字可以修改嵌套作用域 x = x + 7 print("3:",x) sd() print("2:",x) sf() print("1:",x)s()打印
3: 12
2: 12
1: 3