開始使用免費開始

巢狀函式 I

你在上一支影片中學到可以在函式裡再定義函式。這樣做的好處之一,是避免在多個函式中重複寫相同的計算。定義巢狀函式並不特別:就像一般用 def 定義函式一樣,然後把它放進另一個函式裡即可!

在這個練習中,你會在函式 three_shouts() 裡定義一個巢狀函式 inner(),將字串物件與 !!! 串接。three_shouts() 接著會回傳一個包含三個元素的 tuple,每個元素都是透過 inner() 將字串與 !!! 串接後的結果。動手試試看吧!

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 補上巢狀函式的函式標頭:函式名稱為 inner(),且只有一個參數 word
  • 完成回傳值:tuple 的每個元素都要呼叫一次 inner(),並將 three_shouts() 的參數分別作為每次呼叫的引數傳入。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Define three_shouts
def three_shouts(word1, word2, word3):
    """Returns a tuple of strings
    concatenated with '!!!'."""

    # Define inner
    def ____(____):
        """Returns a string concatenated with '!!!'."""
        return word + '!!!'

    # Return a tuple of strings
    return (____, ____, ____)

# Call three_shouts() and print
print(three_shouts('a', 'b', 'c'))
編輯並執行程式碼