"Learning Python with You Hand in Hand" 27-Parameters of Custom Functions

In the last article "Learning Python with You Hand in Hand" 26-Custom Functions , we learned the role of Python custom functions and the syntax and format of custom functions. In this article, we will explain the parameters of the custom function.

The parameters of the custom function are no different from the parameters of the built-in functions that we learned before. They are all in the brackets after the function name, and the parameters of some functions can be empty, and the parameters of some functions can be one or more .

For example, the two custom functions play() and win(A, B) in our previous article on Rolling Dice, one parameter is empty, and the other has two parameters.

In addition, for the same function, the number of parameters is sometimes different. For example, our commonly used print() function can only use the print content as the only parameter, or define the separator parameter sep and the terminator parameter end. At this time, the print() function has multiple parameters.

But this situation does not mean that the number of parameters of the print() function is variable, but that the values ​​of some parameters in the print() function are default. For example, the default value of the sep parameter is a space '', and the default value of the end parameter is a newline character'\n'.

Therefore, when we use the default value of the print() function parameter, the print() function only needs to enter one parameter value; and when we want to modify the parameter with the default value, we need to enter multiple parameters Value, as if the number of parameters of the print() function is changing.

Although the print() function is a built-in function, our custom function can also achieve the same effect by setting default parameter values.

The number of function parameters we mentioned above and the examples of default parameter values ​​belong to the application category of function parameters. In addition, there are keyword parameters and positional parameters and other types, let's take a closer look.

1. Transmission of parameters

In the previous article, we said that after the function is defined in the program, the process of using the function is called the function call, and the first step of the program call is the transfer of parameters, which is to provide the original data we want the function to use to the function the process of.

Look at the simplest example.

In [1]: def qiuhe(a, b):   # 为了便于理解,这里的变量名都是拼音
            he = a + b
            return he
            
        a = 2
        b = 5
        print("a+b的结果是{}。".format(qiuhe(a, b)))

Out[1]: a+b的结果是7。

In the above example, we first defined a function like qiuhe(a, b), and then determined the values ​​of a and b (a more vivid way is to use the input() function to input, which is simplified here for demonstration purposes). When printing the result, the function qiuhe(a, b) needs to be called for calculation. At this time, the process of providing the original data a and b values ​​to the qiuhe(a, b) function is the transfer of parameters.

2. The naming of parameters

The concept of parameter passing just now is very easy to understand and very intuitive. But in most cases, the transfer of parameters is not so intuitive.

The intuition mentioned here means that the variable names of the original data (a and b in the above example) are exactly the same as the parameter names of the function (a and b in the above example). But like the example of the hello(text) function in our previous article, the name of the parameter is text, and the variable name of the original data is a.

Of course, the example just now can also be written in a form where the variable name of the original data is inconsistent with the parameter name of the function, and this inconsistency is our more common way.

Because in a very complex project, the parameter naming rules are very accurate, but you can't just find abcxyz as the parameter name like our example. If this is the case, the readability of the code will be very poor, not to mention the user, but the author may not remember what the previously defined abc parameter means.

Just like the print() function, if the spacer parameter is named a and the terminator parameter is named b, we may have to check the meaning of ab every time to know which parameter we want to pass the value to. But the parameter names sep and end of the print() function are very clear, and it is easy to understand the meaning of each parameter, and it is convenient to use.

The same is true when we customize the function, we must write the meaning of the parameters clearly so that the user can see the meaning of each parameter at a glance. Even very simple functions like ours above can do it.

In [2]: def qiuhe(beijiashu, jiashu):   # 为了便于理解,这里的变量名都是拼音
            he = beijiashu + jiashu
            return he
            
        a = 2
        b = 5
        print("a+b的结果是{}。".format(qiuhe(a, b)))

Out[2]: a+b的结果是7。

Here, we have changed the parameter names of the qiuhe() function to beijiashu and jiashu, so it is easy to know what each parameter of the function means.

Perhaps the effect is not obvious in such a simple example, but you must also develop the habit of naming the parameters accurately, otherwise you will definitely encounter regrets because you forget the meaning of the parameters. It's like we have created countless "new folders" in the computer. When we look for files, we will be at a loss and regret at the beginning, but we can only bite the bullet and look for files one by one, or look at each parameter by parameter. The same.

3. Types of parameters

The problem of parameter naming is solved, but it brings a new problem, that is, the variable name of the original data is different from the parameter name of the function. How are the parameters passed at this time?

This is the focus of this article, which is what we call the types of parameters, including positional parameters, keyword parameters and variable length parameters.

a, location parameters

Positional parameters are our most common type of parameters. Positional parameters must be passed into the function to be called in the correct position (order) and the same number.

The situation mentioned above is a manifestation of positional parameters. That is, although the variable name of the original data is different from the parameter name of the function, as long as the variable with the corresponding position and the same number is provided as the parameter of the function when the function is called, the same name is not required.

In the above example, the parameter names of the function are beijiashu and jiashu, and the variable names provided when calling the function are a and b. Although the names are different, the number is two, and the position of a is the same as that of beijiashu, and the position of b is the same as that of jiashu.

Then when the function is called, the value of a is passed to beijiashu, and the value of b is passed to jiashu, so that the parameter value is passed by "position".

For a, b, beijiashu and jiashu, they also have their own standardized names.

When we define a function, the parameters in parentheses (ie beijiashu, jiashu) are called "formal parameters", which are used to receive parameters and are used as variables inside the function;

When the function is called, the parameters in parentheses (ie a, b) are called "actual parameters", which are used to pass data to the function.

That is, when the type of the parameter is a positional parameter, the name of the formal parameter and the actual parameter are not required to be the same, but the position must be one-to-one, and the number must be exactly the same, otherwise an error will be reported.

Let's look at a few examples.

In [3]: def tixingmianji(shangdi, xiadi, gao):   # 函数名称和参数是不是命名的很准确?
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        h = 3
        print("梯形面积等于{}。".format(tixingmianji(a, b, h)))

Out[3]: 梯形面积等于10.5。

In this example, the top bottom, bottom bottom, and height are all passed to the corresponding parameters of the tixingmianji() function according to the position we specified, and the number is the same, so we get the desired result.

But if the number is the same and the position corresponds to the error, although the program will not report an error, the result will be wrong.

In [4]: def tixingmianji(shangdi, xiadi, gao):
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        h = 3
        print("梯形面积等于{}。".format(tixingmianji(a, h, b)))

Out[4]: 梯形面积等于12.5。

And if the number of parameters is not correct, the program will report an error directly.

In [5]: def tixingmianji(shangdi, xiadi, gao):
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        h = 3
        print("梯形面积等于{}。".format(tixingmianji(a, b)))

Out[5]: ---------------------------------------------------------------------------
        TypeError                                 Traceback (most recent call last)
        <ipython-input-5-4275880fc5c1> in <module>
              6 b = 5
              7 h = 3
        ----> 8 print("梯形面积等于{}。".format(tixingmianji(a, b)))
        
        TypeError: tixingmianji() missing 1 required positional argument: 'gao'

In the error type, the reason for the error is also very intelligently indicated, which is the absence of a positional argument'gao'.

b. Keyword parameters

Positional parameters are very convenient to use, but when there are too many parameter values, it is not easy to remember the position of each parameter. Is there a simpler and more accurate method?

The answer is yes, this is the keyword parameter.

When using keyword parameters, the order of the parameters when calling the function is allowed to be different from the definition when the function is called, but the requirement is that the use of parameter names must be accurate, because the Python interpreter can match parameter values ​​with parameter names.

This is also what we suggest in the naming of the parameters above. The parameter names should be named accurately, not only to facilitate the reading and understanding of the meaning of the parameters, but also to facilitate the call when used as a keyword parameter.

For example, the parameter names of our tixingminaji() function are very easy to identify and use. No matter what the situation or the order, it is easy to pass values ​​for these parameters.

In [6]: def tixingmianji(shangdi, xiadi, gao):
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        h = 3
        print("梯形面积等于{}。".format(tixingmianji(gao = h, xiadi = b, shangdi = a)))

Out[6]: 梯形面积等于10.5。

When shangdi, xiadi, and gao are used as keyword parameters, there is no need to consider the order when calling, just pass all the parameters to the value once.

In addition to solving the problem of poor memory position, keyword parameters can also allow us to define custom functions with default values ​​that have the same effect as print() when used together with positional parameters.

In [7]: def tixingmianji(shangdi, xiadi, gao = 3):
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        print("梯形面积等于{}。".format(tixingmianji(a, b)))

Out[7]: 梯形面积等于10.5。

In this example, we define the default value of gao as 3. Then, as long as the parameter values ​​of shangdi and xiadi are provided, the area of ​​the trapezoid can be calculated. At this time, shangdi and xiadi are position parameters, and parameter values ​​need to be provided according to the position and quantity.

If we still want to use the function of gao whose default value is 3, but the height of the trapezoid to be calculated is 4, then we only need to pass another value to gao.

Just like when we use the print() function, when we don’t need to modify the default values ​​of sep and end (keyword parameters), we only need to provide the content to be printed (positional parameters); and we need to customize sep and end (key (Word parameter), you need to use keyword parameters to pass parameter values ​​to sep and end.

In [8]: def tixingmianji(shangdi, xiadi, gao = 3):
            mianji = (shangdi + xiadi) * gao / 2
            return mianji
            
        a = 2
        b = 5
        h = 4
        print("梯形面积等于{}。".format(tixingmianji(a, b, gao = h)))

Out[8]: 梯形面积等于14。

There are two points that need to be explained:

One is that the position of the keyword parameter must be after the positional parameter, otherwise an error will be reported (positional argument follows keyword argument), and both formal and actual parameters must comply with this rule;

Second, if the position of the positional parameter is still inconvenient to remember, then it can be changed to keyword parameters for use. At this time, there is no need to consider the position.

In the above two situations, you can write your own code to try to verify. For the first point, you can also use xiadi as a keyword parameter to see what effect the positional parameter and the different position and order of the keyword parameter will bring.

c. Variable length parameters

The last parameter type is indefinite length parameter. We don't use this parameter type much at present, so it's just a simple understanding.

Variable-length parameter is a parameter type that can handle more parameters than when defining functions and determining parameters.

This sentence is a bit confusing. In fact, there is a function. Although the number of parameters is limited, it can handle more parameters than when it was defined.

One situation is to add an * sign in front of the parameter, and the parameter with the * sign will receive multiple variables passed in as a tuple.

In [9]: def dayin(canshu1, canshu2, *qitacanshu):    # qitacanshu为接收多于前面两个参数的参数
            print(canshu1, canshu2, qitacanshu, sep = '\n')    # 变量名称不需要加*

        a = 5
        b = 10
        c = 25
        d = 50
        e = 100
        dayin(a, b, c, d, e)

Out[9]: 5
        10
        (25, 50, 100)

Different from positional parameters, you don't need to pass a value to the parameter with *. In this case, this parameter generates an empty tuple. In other words, although the number of parameters seems to be insufficient, in fact no error will be reported.

In [10]: def dayin(canshu1, canshu2, *qitacanshu):
             print(canshu1, canshu2, qitacanshu, sep = '\n')
             
         a = 5
         b = 10
         dayin(a, b)   # 看上去参数好像少了一个,但不会报错

Out[10]: 5
         10
         ()

Another situation is to add two * signs in front of the parameters. At this time, the parameters with ** signs will receive multiple variables passed in as a dictionary.

In [11]: def dayin(canshu1, canshu2, **qitacanshu):    # qitacanshu为接收多于前面两个参数的参数
         print(canshu1, canshu2, qitacanshu, sep = '\n')    # 变量名称不需要加**

         a = 5
         b = 10
         c = 25
         d = 50
         e = 100
         dayin(a, b, key1 = c, key2 = d, key3= e)   # 因为是字典的形式,所以要提供key值

Out[11]: 5
         10
         {'key1': 25, 'key2': 50, 'key3': 100}

Although the variable length parameter will not be exposed too much in our current learning stage, because it can generate two very commonly used data structures-tuples and dictionaries, it can play a very important role in some cases .

The above is our introduction to the parameters of custom functions. After understanding the transfer method and naming method of function parameters, we focus on the application of positional parameters and keyword parameters. Although the explanation of variable length parameters is relatively basic, this preliminary concept may provide us with a new way of solving problems in the future.

In the next article, we will continue to explain custom functions, mainly the introduction and application of function return values, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

"Learning Python with You Hand in Hand" 24-Collection

"Learning Python with You Hand in Hand" 25-List Comprehension

"Learning Python with You Hand in Hand" 26-Custom Functions

For Fans: Follow the "also said Python" public account, reply "Hand 27", you can download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers
 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/105625808