開始使用免費開始

關鍵字 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'
____
編輯並執行程式碼