Talk briefly about the variable parameters of functions in Python

  • 2020-05-10 18:24:41
  • OfStack

preface

In Python, you can define a function with required, default, variable, and keyword parameters, all of which can be used in one or only some of them, but note that the order in which the parameters are defined must be: required, default, variable, and keyword parameters.

Variable parameter (*)

Variable parameters, as the name implies, its parameters are variable, such as lists, dictionaries, and so on. If we need a function to handle a variable number of arguments, we can use variable arguments.

When we look at a lot of Python source code, we will often see some function (* parameter 1, ** parameter 2) such as the function definition, the * parameter and ** parameter are variable parameters, 1 will be a little confusing. Once you've defined the variable parameters of a function, it's not that hard to understand.

When we don't know how many parameters we need to define a function, mutable parameters can play a big role.

In Python, parameters with * are used to accept a variable number of parameters.

If 1 function is defined as follows:


def functionTest(*args): 
 .... 
 .... 
 ....

We can call it as follows:


functionTest(1) 
 or  
functionTest(1,2) 
 or  
functionTest(1,2,3)

You can pass in more than one parameter later.

Take a look at the sample code and see how * works:


def get_sum(*numbers): 
 sum = 0 
 for n in numbers: 
  sum += n 
 return sum 
  
# Write your code here to call get_sum To find 5 The sum of two Numbers and output the result  
print (get_sum(1,2,3,4,5))

What's the result? You can see it with your own hands, so it is about the whole content of variable parameters in Python function. I hope this article can be helpful for you to learn or use python. If you have any questions, please leave a message to communicate.


Related articles: