關鍵字 nonlocal 與巢狀函式
再來加強你對於作用域的掌握吧!在這個練習中,你會在巢狀函式中使用關鍵字 nonlocal,用來修改外層作用域中定義的變數值。
本練習屬於課程
Python 函式入門
練習說明
- 將
echo_word指派為字串word自己與自己串接的結果。 - 使用關鍵字
nonlocal,以修改外層作用域中的echo_word值。 - 將
echo_word改成echo_word與 '!!!' 串接的結果。 - 呼叫函式
echo_shout(),並傳入單一引數 'hello'。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define echo_shout()
def echo_shout(word):
"""Change the value of a nonlocal variable"""
# Concatenate word with itself: echo_word
____
# Print echo_word
print(echo_word)
# Define inner function shout()
def shout():
"""Alter a variable in the enclosing scope"""
# Use echo_word in nonlocal scope
____
# Change echo_word to echo_word concatenated with '!!!'
echo_word = ____
# Call function shout()
shout()
# Print echo_word
print(echo_word)
# Call function echo_shout() with argument 'hello'
____