非局部语句nonlocal 与 全局变量声明global
程序员文章站
2024-02-17 21:49:52
...
global 是将一个全局变量声明的关键字。
global 示例:
pi = 3.141592653589793
e = 2.718281828459045
def my_f():
global pi
pi = 6
print("global pi :",pi)
e = 2.718
print("局部变量 e :",e)
print(pi)
print(e)
my_f()
print(pi)
print(e)
结果:
非局部语句nonlocal 示例:
def outer_f():
tax = 0.17
print("外层函数的局部变量: ",tax)
def inner_f():
nonlocal tax
tax = 0.05
print("内层函数的局部变量",tax)
inner_f()
print("外层函数的局部变量",tax)
outer_f()
结果: