Python Tutorial 25 Detailed explanation of parameter types in Python

Mondo Technology Updated on 2024-02-18

When we write a function, we define some placeholders, which are parameters, which are the placeholders used in the function definition to receive the externally passed value, which will help us receive the externally passed value when the function is called. In Python, there are various types of parameters, including positional parameters, default parameters, keyword parameters, variable positional parameters, variable keyword parameters, and forced keyword parameters.

Positional arguments are the most common type of arguments, and they are also the default parameter types. They are passed in the order in which they appear in the function definition and must be provided sequentially when the function is called.

def greet(name, message):

print(message, name)

greet("alittle", "hello"Output: hello alittle

Default arguments are those parameters that have a default value when the function is defined, and when the function is called, if no specific value is provided for the parameter, then the default value will be used as the value of the parameter. By setting default values for parameters, you can make functions more flexible and easy to use in certain situations. If the function is called without providing a value for that parameter, the function uses the default value, otherwise it uses the value passed to the parameter.

def greet(name, message="hello"):

print(message, name)

Call the function with the default parameters.

greet("alittle"Output: hello alittle

Passing a specific parameter value calls the function.

greet("kobe", "hi"Output: Hi Kobe

It is important to note that in Python, the default parameters are set sequentially from left to right, and if you want to set a default value for the first parameter, you have to make sure that it precedes the following parameter. That is to say, to set a default value for the penultimate parameter, you must first set a default value for the penultimate parameter.

def greet(name="iverson", message):

print(message, name)

Since the first parameter has a default value, only the second parameter can be passed.

greet("kobe")

When the above example is run, an error message is reported:

file "d:\program files\jetbrains\pycharmprojects\hello.py", line 33

def greet(name="iverson", message):

syntaxerror: non-default argument follows default argument

A syntax error occurs when trying to set a default value for the first parameter. This is because when defining a function, the default argument can only be placed after the non-default argument. So if we want to set a default value for the first parameter, we can consider using a keyword parameter to pass the parameter value, or the two parameters can be reversed.

Keyword arguments are a way to specify the value of a parameter using the name of the parameter when a function is called. Using keyword arguments can make function calls clearer and more readable, especially when a function has multiple arguments and they have the same data type or default value.

For example, the example of the default parameter above:

def greet(name, message):

print(message, name)

Call the function with keyword arguments.

greet(name="iverson", message="hello"Output: hello iverson

greet(message="hi", name="kobe"Output: Hi Kobe

In the above example, we specified the parameter value by the parameter name when the function was called. This not only allows the parameters to be passed accurately, but also makes the intent of the function call clearer and more understandable. Even if the first parameter in the function definition is set to a default value, it will not be error-corrected.

Therefore, you can use keyword arguments to specify the parameter name explicitly, which can avoid errors caused by the wrong order of the parameters. And only pass values to the parameters you care about, ignoring the others. Provides better readability and maintainability when the function is called.

Variable length positional arguments are a property that allows a function to accept any number of positional arguments. When defining a function, an asterisk (*) is used as a prefix to denote a variable positional parameter. It packs all the incoming positional parameters into a tuple. When the function is defined, we can use *args in the parameter list to receive these parameters.

def calculate_sum(*numbers):

total = 0

for num in numbers:

total += num

return total

print(calculate sum(1, 2, 3)) Output: 6

print(calculate sum(4, 5, 6, 7, 8)) output: 30

It is also important to note that the variable positional parameters are placed after the other parameters. That is, the parameters defined first in the function definition will read the values of the arguments in order of position, while the variable positional arguments will read all the remaining arguments. For example, if you want to write like this, you will get an error:

def calculate_sum(*numbers, message):

total = 0

for num in numbers:

total += num

return message, total

result = calculate_sum(1, 2, 3, "sum=")

print(result)

If you run it, the following error will be reported.

traceback (most recent call last):

file "d:\program files\jetbrains\pycharmprojects\hello.py", line 40, in

result = calculate_sum( 1, 2, 3, "sum=")

typeerror: calculate_sum() missing 1 required keyword-only argument: 'message'

Variable keyword arguments are defined by using the ** prefix to receive any number of keyword arguments. Somewhat similar to the key, value format, it will package all the incoming keyword arguments into a dictionary (dict), which can be accessed inside the function using key-value pairs.

def calculate_sum(*args, *kwargs):

total = sum(args)

for key, value in kwargs.items():

total += value

return total

result = calculate_sum(1, 2, 3, num1=4, num2=5)

print(result) output: 15

In this example,calculate_sumFunctions accept variable positional parametersargsand variable keyword parameterskwargs。Variable positional parametersargsUsed to receive any number of positional arguments, while variable keyword arguments are availablekwargsUsed to receive any number of keyword parameters. Inside the function, we start by usingcalculate_sumFunction pair variable positional parameterargsMake a sum. We then iterate through the variable keyword argumentskwargsto add up the values of the keyword parameter to the sum.

Variable keyword arguments provide a flexible way to handle an indeterminate number of keyword arguments and provide greater scalability and adaptability to functions.

The mandatory keyword-only arguments are at 3Introduced after version 1, it means that when a function is defined, the * suffix is used to restrict the use of keyword arguments when calling functions, and positional arguments are not allowed.

def greet(*,name, message): Use the separator "*" to indicate that the following argument must be passed using a keyword. 

print(message, name)

greet(name="alittle", message="hi") keyword parameter passing.

greet("kobe", "hi")

The first callgreetThere is no problem, but the second place is calledgreetIt will throw an exception and report an error.

traceback (most recent call last):

file "d:\program files\jetbrains\pycharmprojects\hello.py", line 39, in

message = greet("kobe", "hi")

typeerror: greet() takes 0 positional arguments but 2 were given

By using mandatory keyword arguments, we can clearly convey the meaning of the arguments, avoid confusion about the position of the arguments, and improve the readability and robustness of the parameters.

Related Pages