Python: variadic parameters(*) and keyword parameters(**)

There is a question:

I want to define a function to add all elements in a list that I created just now,how can I do that?

Here is the common answer:

def add(my_list):
    sum = 0   
    for list in my_list:
        sum = sum+list
    return sum
my_list = [1,2,3]
result = add(my_list)    

Now let's expand this question:

If I want to add 2 variables,but if there is just one number or more than 2 variables,it' ok,I just want the first variable can join the calculation.how can I define a function to do this?

def add2(a,*b):
    if len(b) == 0:
        return a
    sum = a + b[0]
    return sum
v_a = 3
v_b = 4
v_c = 5
result2 = add2(v_a,v_b,v_c)
result3 = add2(v_c)
print(result2,'\n',result3)
7 
5

Futhermore,if I want to register your information,There are some mandatory options and some optional.how can I define a function to reach it?

def infor(name,age,**address):
    print(name)
    print(age)
    print(address)

infor("ye","security",my_address = "shanghai")
infro("ye","security",my_address = "shanghai",likes = "haha")
output:

ye
security
{'my_address': 'shanghai'}

 ==========here is a line============= 

ye
security
{'my_address': 'shanghai', 'likes': 'haha'}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值