添加可变参数
Python 允许自定义函数通过"可变参数"接收任意数量的位置参数。这种灵活性使函数可以用多种方式调用,同时仍能产生预期结果。
利用这一能力,您将编写一个函数来连接(拼接)字符串——无论提供了多少段文本都可以!
本练习是课程的一部分
Python 中级:面向开发者
练习说明
- 定义一个名为
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!"))