1. 程式人生 > >Python學習14--函式2(函式作用域)

Python學習14--函式2(函式作用域)

#Author:Du Yang 
#Data:2018/7/19
count = 10
#區域性變數不能直接對全域性變數進行修改
def F():
    global count#必須宣告count為全域性變數才能引用全域性變數;
                #如實若是為未宣告,則語句會只會在函式的作用域中查詢count變數,所以錯誤
    count += 1
    print(count)


def outer():
    count = 999
    def inner():
        nonlocal  count#測試時候將該句刪去,檢視區別
        count = 20
        print(count)
    inner()
    print(count)

outer()
#總結:
#   在不同函式作用域中加入“nonlocal 變數名” 和 ”global 變數名“ 的作用在於,
#   希望使用上一層函式(作用域)中的變數值

 首先明確只有模組(module),類(class)以及函式(def、lambda)才會存在作用域的問題,if和for等沒有作用域這一說