python——函数 14、global与nonlocal

1、global:在局部修改全局变量

x=100
def foo():
    global x
    x=200
foo()
print(x)
#todo 如果不写global,则打印为100
View Code

2、nonlocal:只在函数内部找变量,如果没有则报错

x=100
def a():
    x=200
    def b():
        x=300
        def c():
            nonlocal x
            x=1000
        c()
        print(x)
    b()
a()
View Code

猜你喜欢

转载自www.cnblogs.com/StevenSunYiwen/p/8954308.html