開始使用免費開始

加入任意引數

Python 允許自訂函式透過「任意引數」來接受不定數量的位置引數。這種彈性讓函式能以多種方式使用,同時仍能產生預期的結果。

運用這個特性,你將撰寫一個函式來串接(合併)字串,不論提供多少段文字都能接在一起!

本練習屬於課程

Intermediate Python for Developers

檢視課程

練習說明

  • 定義一個名為 concat() 的函式,接受名為 args 的任意引數。
  • 使用 for 迴圈遍歷 args 中的每個 arg
  • 呼叫該函式,測試是否正確運作。

動手互動練習

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

# Define a function called concat
def ____(____):
  """Concatenates multiple string arguments with spaces between them."""

  result = ""

  # Iterate over the Python args tuple
  for ____ in ____:
    result += " " + arg
  return result

# Call the function
print(____("Python", "is", "great!"))
編輯並執行程式碼