There are four ways to define parameters in Python functions

  • 2020-04-02 14:26:58
  • OfStack

Function parameters are defined in Python in four main ways:

1. F (arg1, arg2,...).

This is the most common way to define a function, a function can define any number of parameters, each parameter is separated by a comma, in this way the function defined in the call must also provide the number of equals in the function name after the curly braces
And the order must be the same, that is, the number of arguments and arguments must be the same in this way, and they must correspond one to one, that is, the first parameter corresponds to the first argument. Such as:


def a(x,y):print x,y

Call this function, a(1,2), then x is 1, y is 2, corresponding to the form participation argument, if a(1) or a(1,2,3) will report an error.

2. F (arg1, arg2 = value2,...).

This is an improved version of the first, with default values, such as:


def a(x,y=3):print x,y

If I call this function, a(1,2) is still x equals 1 and y equals 2, but if I call a(1), I'm not going to get an error, so x is still 1 and y is the default 3. In the above two ways, we can also change the parameter position, for example, a(y=4,x=3) is also acceptable in this form.

3. (F * arg1)

The above two methods are to pass in as many arguments as there are parameters, but sometimes it is not certain how many parameters, then the third method is more useful, it is a * with the parameter name to represent the function
The number of arguments doesn't matter, it could be zero or it could be n. Note that no matter how many there are, they are stored inside the function in a tuple with the parameter named identifier.


def a(*x):print x


>>> a(1,2,3)
(1, 2, 3)
>>> a(x=1,y=2,z=3)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: a() got an unexpected keyword argument 'x'

4. F (arg1) * *


Two * before the parameter name indicates that the argument will be stored inside the function in a dictionary of the form named identifier, and the method to call the function needs to be in the form of arg1=value1 and arg2=value2.


def a(**x):print x


>>> a(x=1,y=2,z=3)
{'y': 2, 'x': 1, 'z': 3} # In the dictionary 
>>> a(1,2,3) # This call reports an error 
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: a() takes exactly 0 arguments (3 given)

Related articles: