Quick actions

cmd+k|ctrl+k

Navigation

Languages

global

Snippet info

Language

Python

Visibility

public

Author

fai

Created

2024-10-05T02:22:39.538894Z

Updated

2024-10-05T02:43:03.964582Z

def a():
    print(x)
y = 0
def b():
    global x # x can't be change to 'nonlocal x, or error will arise'
    x = 1
    y = 2
    def c():
        nonlocal y
        y = y + 1
        def d():
            nonlocal y
            y = y + 1
#            print(y)
            a()
        d()
    c()
    print(y)
b()
# in python, to make it easier to learn, it uses indent, with no {} to declare variable in functions
# to know how the variables from various functions, it uses global, nonlocal here in this example
# by using global, variable x can go to and from the functions wherever 'global' is define
# by using nonlocal, variable outside the upper level can be changed. Like the y in function d
# function only runs with codes inside when it is called and point to the address it is located
# to have no conflict between global and nonlocal, 
# nonlocal can only be used up to the 2 layers of functions, say function b, in this case
INFO