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'}