知行编程网知行编程网  2022-11-20 07:30 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python如何传递任意数量的实参的相关知识,希望可以帮到处于编程学习途中的小伙伴


Python如何传递任意数量的参数


传递任意数量的实参

在形参前加一个*,Python会以形参的名字创建一个空元组,并将所有接收到的值放入这个元组中 :

def make_pizza(*toppings):
    print("\nMaking a pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)
make_pizza('pepperoni')
make_pizza('mushroom', 'green peppers', 'extra cheese')

不管函数收到多少实参,这种语法都管用。


1. 结合使用位置实参和任意数量实参

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings: ")
    for topping in toppings:
        print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushroom', 'green peppers', 'extra cheese')

运行结果:

Making a 16-inch pizza with the following toppings: 
- pepperoni
Making a 12-inch pizza with the following toppings: 
- mushroom
- green peppers
- extra cheese


2. 使用任意数量的关键字实参

def build_profile(first, last, **user_info):
    profile = dict()
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physic')
print(user_profile)

形式参数**user_info 中的两个星号导致 python 创建一个名为 user_info 的空字典。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享