Python Tutorial - Function Keyword Arguments

Python Exercise Lists

So far, the parameters we have used when using functions are positional parameters, that is, the actual parameters passed into the function must correspond to the number and position of the formal parameters. The keyword parameters introduced in this section can avoid the trouble of remembering the parameter position then make the function call and parameter passing more flexible and convenient.

The keyword parameter is to use the name of the formal parameter to determine the input parameter value. When specifying function arguments in this way, you no longer need to be completely consistent with the position of the formal parameters, as long as the parameter names are written correctly.

Therefore, the parameter names of Python functions should have better semantics, so that the program can immediately understand the meaning of each parameter passed to the function.

For example, the following program uses keyword arguments to pass parameters to functions:

def dis_str (str1, str2):
    print ("str1:", str1)
    print ("str2:", str2)
#Position parameters
dis_str ("", "")
#Keyword parameters
dis_str ("", str2 = "")
dis_str (str2 = "", str1 = "")

The program execution result is:


It can be seen that when calling a parameterized function, it can be called according to the position parameter, or it can be called using the keyword parameter (line 8 in the program). When using a keyword parameter call, the position of the parameter passing can be arbitrarily swapped.

Of course, you can also pass position parameters and keyword parameters in the same way as in line 7. However, it should be noted that keyword parameters must be placed after all positional parameters when mixing parameters. In other words, the following code is wrong:

# Position parameter must be placed before keyword parameter, the following code is wrong
dis_str (str1 = "", "")

The Python interpreter reports the following error:

File "[ipython-input-4-600f2deb36ad]", line 2
dis_str (str1 = "", "")
SyntaxError: positional argument follows keyword argument

Python Function Default Parameter Settings

We know that if you don't specify a parameter when calling a function, the Python interpreter will throw an exception. To solve this problem, Python allows you to set a default value for the parameter, which is to specify a default value for the formal parameter directly when defining the function. In this case, even if no parameter is passed to a parameter with a default value when the function is called, the parameter can directly use the default value set when the function is defined.

Python defines a function with default parameters, and its syntax is as follows:

def function name (..., formal parameter name, formal parameter name = default value):
         Code block

Note that when using this format to define a function, the formal parameter specified with a default value must be at the end of all parameters without a default value, otherwise a syntax error will occur.

The following program demonstrates how to define and call a function with default parameters:

# str1 has no default parameters, str2 has default parameters
def dis_str (str1, str2 = ""):
    print ("str1:", str1)
    print ("str2:", str2)
dis_str ("") # line 6
dis_str ("", "")

The output is:


In the above program, the dis_str () function has 2 parameters, and the second one has default parameters. This means that when calling the dis_str () function, we can pass in only one parameter, which will be passed to the str1 parameter, and str2 will use the default parameters, as shown in line 5 of the program.

Of course, when calling the dis_str () function, you can also pass values to all parameters (as shown in line 6), and even if str2 has a default value, it will take precedence over the new value passed to it.

At the same time, in combination with keyword parameters, the following three ways to call the dis_str() function are also possible:

dis_str (str1 = "")
dis_str ("", str2 = "")
dis_str (str1 = "", str2 = "")

The output is:


Again, when defining a function with default parameters, parameters with default values must come after all parameters without default values. Therefore, the function defined in the following example is incorrect:

#Grammatical errors
def dis_str (str1 = "", str2, str3):

The output is:

File "[ipython-input-7-ab2ed54a3aac]", line 2
def dis_str (str1 = "", str2, str3):
SyntaxError: non-default argument follows default argument

Obviously, str1 has a default value, and str2 and str3 have no default value, so str1 must come after str2 and str3.

Some readers may ask, for a custom function, you can easily know which parameters have default values, but if you use built-in functions provided by Python or other third-party functions, how do you know which parameters have default values?

In Pyhton, you can use "function name .__ defaults__" to view the current value of the function's default value parameter, and the return value is a tuple. Taking the dis_str () function in this section as an example, based on this, execute the following code:

print (dis_str.__defaults__)

The output is:



More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises