def make_pizza(*toppings):
print(toppings)
#打印所有的配件
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
----------
Result
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
形参名*topping的星号创建一个名为toppings的元组。函数传递的所有实参都将放入这个元组内。
1.结合使用位置实参和任意参数实参
在函数定义中将接纳的任意数量实参的形参放在最后,python先匹配位置实参和关键字实参,在将余下的实参都收集到最后一个形参中。此时只有一个位置实参。
def make_pizza(size,*toppings):
print("\nMakeing a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#打印所有的配件
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
----------
result:
Makeing a 16-inch pizza with the following toppings:
- pepperoni
Makeing a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese
2.使用任意数量的关键字实参
在函数中传递实参**Variable代表该实参是任意成员的字典。
def build_profile(first, last, **user_info):
profile = {}
profile['first'] = first
profile['last'] = last
for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('赵', '四',
location = '安徽', filed = '种地')
#后面两个参数传递键-值对
print(user_profile)
----------
Result:
{'first': '赵', 'last': '四', 'location': '安徽', 'filed': '种地'}