網頁

2018年10月16日 星期二

[python]python 變數宣告 global and nonlocal


def outer():
    
    def inner():
        global a
        a = 15
        print ("inner:", a)
        
    a = 10
    print("outer1:", a)
    inner()
    print("outer2:", a)

a = 5
print("main1:", a)
outer()
print("main2:", a)

output:
main1: 5
outer1: 10
inner: 15
outer2: 10
main2: 15

def outer():
    
    def inner():
        nonlocal a
        a = 15
        print ("inner:", a)
        
    a = 10
    print("outer1:", a)
    inner()
    print("outer2:", a)

a = 5
print("main1:", a)
outer()
print("main2:", a)

output:
main1: 5
outer1: 10
inner: 15
outer2: 15
main2: 5

沒有留言:

張貼留言