I have been learning Python by myself recently. Python is really a good thing, two words, concise, the original function that can only be achieved by writing n lines in Java, Python may be done in a few lines. Closer to home, today I'm going to talk about variable parameter functions in Python.
The variable parameter function can be realized by using * when defining the function.
E.g:
We ask for the sum of several numbers
#求和
def getSum(y,*x):
sum = y
for i in x:
sum+=i
print(*x)
return sum
print(getSum(1,2,3,4,5))
*x, we can think of it as a tuple. When calling this function, the first parameter 1 will be passed to y, and the remaining parameters form a tuple and passed to *x. Therefore, the value of *x The value is (2,3,4,5).
Let's look at another form below.
We can also use arbitrary key-value pairs as parameters, which can be achieved by using ** when defining functions.
E.g:
#求和
def getSum(x,**y):
sum = x
for k,v in y.items():
print('添加 {} 键,对应值为{}:'.format(k,v))
sum+=v
return sum
print(getSum(1,n=2,y=3,z=4,m=5))
**y is actually a dictionary type.
That's it for today's sharing!