任意關鍵字引數
任意位置引數是建立自訂函式時增加彈性的一種方式,但你也可以使用任意關鍵字引數。
你的目標是把你在上一個練習建立的 concat 函式修改為可接受任意關鍵字引數。
本練習屬於課程
Intermediate Python for Developers
練習說明
- 將
concat()定義為接受名為kwargs的任意關鍵字引數的函式。 - 在函式內,使用
kwarg作為迭代器來迴圈遍歷關鍵字引數的「值」。 - 使用關鍵字引數呼叫
concat():start設為"Python",middle設為"is",end設為"great!"。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Define a function called concat
def ____(____):
"""Concatenates keyword arguments into a single string with spaces."""
result = ""
# Iterate over the Python kwargs
for ____ in kwargs.____():
result += " " + kwarg
return result
# Call the function
print(____(____="Python", ____="is", ____="great!"))