1. 程式人生 > >python中有關函式的全域性變數和區域性變數

python中有關函式的全域性變數和區域性變數

例一:

a = 9
def b():
    print(a)
結果打印出來是:9
a 是定義在函式外部的全域性變數,在函式內部可以使用。

例二:

a = 4
def b():
    a = 8
    print(a)
b() 
print (a)   
執行結果是:8,4
在函式內部定義的a 是區域性變數,當我們呼叫函式b的時候,函式內部列印的是區域性變數,函式外部列印的是全域性變數a,並沒有改變外部的全域性變數。
如果你想在函式內部改變全域性變數的值,就要使用global關鍵字
 a = 8
 def b ():
     global a
     a = 2
     print(a)
b()
print(a)
執行結果是:2
2

例三:

def make_counter():
    count = 0 
    def counter():
        count = 5 
        count += 1
        return count
    print(counter())
    print(count)
執行結果是 60
要想在巢狀函式內部修改區域性變數的值,可以使用nonlocal關鍵字
def make_counter():
    count = 0 
    def counter():
        nonlocal count 
        count  =+ 1
return count print(counter()) print(count) 執行結果是:11