開始使用免費開始

含可變長度關鍵字引數的函式(**kwargs)

讓我們把「彈性引數」再往前推進一些——你已經使用過 *args,接下來要用 **kwargs**kwargs 的不同之處在於,它允許你將可變數量的「關鍵字引數」傳入函式。回想上一部影片提到的,在函式定義內,kwargs 是一個字典。

為了更好地理解這個概念,你將在本練習中用 **kwargs 來定義一個可接受任意數量關鍵字引數的函式。這個函式會模擬一個簡單的狀態回報系統,列印電影中某個角色的狀態。

本練習屬於課程

Python 函式入門

檢視課程

練習說明

  • 用函式名稱 report_status 補完整函式標頭。它只接受一個彈性引數 **kwargs
  • 逐一走訪 kwargs 的鍵值配對,並以冒號 ':' 分隔列印鍵與值。
  • 第一次呼叫 report_status() 時,傳入以下關鍵字對應值:name="luke"affiliation="jedi"status="missing"
  • 第二次呼叫 report_status() 時,傳入以下關鍵字對應值:name="anakin"affiliation="sith lord"status="deceased"

動手互動練習

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

# Define report_status
def ____(____):
    """Print out the status of a movie character."""

    print("\nBEGIN: REPORT\n")

    # Iterate over the key-value pairs of kwargs
    for ____, ____ in kwargs.items():
        # Print out the keys and values, separated by a colon ':'
        print(____ + ": " + ____)

    print("\nEND REPORT")

# First call to report_status()


# Second call to report_status()
report_status(name=____, affiliation=____, status=____)
編輯並執行程式碼