開始使用免費開始

可變長度引數(*args)的函式

彈性引數可以讓你把可變數量的引數傳給函式。在這個練習中,你會練習定義一個能接受可變數量字串引數的函式。

你要定義的函式是 gibberish(),它可以接受可變數量的字串值。它的回傳值是一個單一路字串,內容是依照呼叫時的順序,把所有傳入的字串引數串接起來。你會先用一個字串引數呼叫這個函式,接著再用多個字串引數呼叫,觀察輸出如何改變。回想上一支影片所示,在函式定義中,args 是一個 tuple。

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 以函式名稱 gibberish 完成函式標頭。它接受一個彈性引數 *args
  • 宣告變數 hodgepodge,並將其初始化為空字串。
  • 在函式本體的最後回傳變數 hodgepodge
  • 以單一字串 "luke" 呼叫 gibberish()。將結果指定給 one_word
  • 按下 Submit 按鈕,使用多個引數呼叫 gibberish(),並在 Shell 中列印其值。

動手互動練習

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

# Define gibberish
def ____(____):
    """Concatenate strings in *args together."""

    # Initialize an empty string: hodgepodge
    

    # Concatenate the strings in args
    for word in args:
        hodgepodge += word

    # Return hodgepodge
    ____

# Call gibberish() with one string: one_word
one_word = ____

# Call gibberish() with five strings: many_words
many_words = gibberish("luke", "leia", "han", "obi", "darth")

# Print one_word and many_words
print(one_word)
print(many_words)
編輯並執行程式碼