python学习笔记(八)传递任意数量的实参

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': '种地'}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值