开始使用免费开始使用

任意关键字参数

任意位置参数是创建自定义函数时提升灵活性的一种方式,但您也可以使用任意关键字参数。

您的目标是基于上一个练习中创建的 concat 函数,将其修改为可以接受任意关键字参数。

本练习是课程的一部分

Python 中级:面向开发者

查看课程

练习说明

  • 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!"))
编辑并运行代码