Like the C language, there are variadic functions in Python, where a function can receive multiple parameters, and the number of these parameters is unknown prior to the function call. In this article, let's introduce the mutable parameters in Python.
">
Objective
Defining functions in Python can be done with required parameters, default parameters, variable parameters, and keyword parameters, all of which can be used together, or only some of them, but note that the order of the parameters definition must be: required, default, variable, and keyword parameters. 4
Variable parameters (*)
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 parameters, we can use variable parameters.
When we look at a lot of Python source code, we often see a function (* parameter 1, * * Parameter 2) Such a function definition, the * parameter and the * * parameter is a variable parameter, for a moment will be a bit confusing. In fact, as long as the definition of variable parameters of the function is clear, it is not difficult to understand.
When we don't know how to define a function with a few parameters, variable parameters can be used.
In Python, the parameter with * is used to accept a variable number of parameters.
If a function is defined as follows:
def functiontest (*args): ... . .... ....
Called when we can call this:
FunctionTest (1) or functiontest (or functiontest)
You can pass in multiple parameters later.
Take a look at the example code and see how it applies:
def get_sum (*numbers): sum = 0 for n in numbers: sum + = n return sum #在这里写下你的代码来调用get_sum来求5个数字的和, and output this result print (Get_sum (1,2,3,4,5))
What would be the result? Everyone can do their own operation to see, in order to be about the function of the variable parameters in Python all content, I hope this article for you to learn or use Python can help, if there is doubt can message exchange.