global:
在函数中修改全局变量的值
#未使用global关键字 number = 10 print(number) def fun1(): number = 5 #函数中出现的全局变量被替换为一个同名的新变量 print(number) fun1() print(number) ====== 10 5 10
#使用global关键字 number = 10 print(number) def fun1(): global number #使用关键字的时候不能赋值,会报错 number = 5 print(number) fun1() print(number) ====== 10 5 5
nonlocal:
在嵌套的函数中内部函数修改外部函数的局部变量
#嵌套函数未使用nonlocal def fun1(): a = 5 print(a) def fun2(): a = 3 print(a) fun2() print(a) fun1() ====== 5 3 5
#嵌套函数使用nonlocal def fun1(): a = 5 print(a) def fun2(): nonlocal a a = 3 print(a) fun2() print(a) fun1() ====== 5 3 3
错误用例:
#想对全局变量进行nonlocal number = 10 print(number) def fun1(): nonlocal = 5 #必须是嵌套的函数 print(number) fun1() print(number) ====== invalid syntax