在區域作用域之外修改變數
有時候你的函式需要修改位於該函式區域作用域之外的變數。雖然一般來說不建議這麼做,但在必要時知道如何操作仍然很重要。請更新這些函式,讓它們能修改通常不在其作用域內的變數。
本練習屬於課程
Python 函式寫作
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
call_count = 0
def my_function():
# Use a keyword that lets us update call_count
____ call_count
call_count += 1
print("You've called my_function() {} times!".format(
call_count
))
for _ in range(20):
my_function()