python - function 14, global and nonlocal

1. global: modify global variables locally

x=100
def foo():
    global x
    x=200
foo()
print (x)
 # todo prints 100 if global is not written
View Code

2, nonlocal: only find variables inside the function, if not, an error will be reported

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

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324975777&siteId=291194637