Type and usage of Python function parameters

Python functions are easy to use because they can pass parameters to achieve flexible use in different scenarios Type of function parameter Xiaobian summarized six different forms. Let's learn one by one.

Let's start with a question: use a function to print the results of 3 * 2, 3 * 3 and 3 * 4.

Under normal circumstances, you may directly encapsulate a function to complete the multiplication of these three numbers in the function body, as follows.

def p_num():
    print(3 * 2)
    print(3 * 3)
    print(3 * 4)

Return result:


The above results meet the requirements of the topic. At this time, if there is another problem: use a function to output the results of 5 * 2, 5 * 3 and 5 * 4.

At this time, you will find that you must encapsulate a function to achieve this effect, but many students will find that this effect is very similar to our above effect. Some students will think, can we use a variable to replace 3 in the function in question 1? Congratulations, python also thinks so, so we introduce the concept of parameter. Let's see how Python implements it.

1, Single parameter transfer of function

def p_num(n): # Set a formal parameter n
    print(n * 2)
    print(n * 3)
    print(n * 4)
p_num(5) # The passed argument is 5

N in the above function is a formal parameter. You can also understand it as a variable name. When calling the function, the actual parameter should be passed in parentheses. You can understand it as the value assigned to the above formal parameter (variable). In this way, what value you assign to n is what value is involved in the operation in the function body. In this way, we can realize different numbers and realize the same method above. One function is done.

2, Multiparameter transfer

In other words, if we want to get the value of multiplication and subtraction of two numbers, and the two numbers will change at any time in different scenarios, how can we achieve it? It is estimated that some students have thought of it. Just change one formal parameter of the above function into two. Yes, that's it. Let's demonstrate.

def test():
    print(5 * 3)
    print(5 - 3)
# 1. Fixed parameter def test(m,   n):
    print(m * n)
    print(m - n)
test(5, 3)
test(985, 211)

3, Keyword parameters

Repeatedly output a string n times through a function. Note that n here represents an unknown number of times, and the string is also an unknown string. We can see from this topic that it must belong to a multi parameter function. Then it is very simple to implement, as follows.

def test(num, str):
    print(str * num)
test('www.wakey.com.cn', 5)

At this time, you can see that the output result is also correct, but we want to insert num=5, str='www.wakey.com.cn ', and the parameters in the function are inserted in order. Therefore, although the result is no problem, there will be unnecessary errors in some scenarios. For example, we need to process the string str and then calculate it. At this time, python introduces keyword parameters to specify the relationship between formal parameters and arguments.

def test(num, str):
    print(str * num)
test(str='www.wakey.com.cn', num=5)

4, Default parameters

Another scenario appears at this time, that is, the above string is www.wakey.com.cn in most cases, and other strings occasionally occur. If the above keyword parameters are used, you must enter a fixed value every time. This is more troublesome to write, so let's see how the default parameters solve this problem.

def test(num, str='www.wakey.com.cn'):
    print(str * num)
test(num=5, str='www')

The default parameters here can also be called default value parameters, that is, when parameters are not passed, use their own default values, and when parameters are passed, use the arguments passed in.

5, Indefinite length parameter tuple

If a function does not know how many parameters it will receive in the future, it can use a tuple to accept indefinite length parameters. The following is a direct implementation of the effect.

def test(*m): # A * sign is added here to accept parameters as tuples, which is generally written as: * args
    print(m) # Note that the formal parameter here cannot be marked with an *
test((3, 5, 7))
test(3, 5, 7)

Note that the results of the two calls here are tuples, but the results are different. Look at the returned results.

((3, 5, 7),)
<class 'tuple'>
(3, 5, 7)
<class 'tuple'>

6, Indefinite length parameter dictionary

Another situation is that each parameter has its own meaning, but it is not a fixed parameter. Here, you can use the key value pair feature of the dictionary to implement it.

def test(**m): # Two * signs are added here to accept parameters as a dictionary, which is generally written as: * * kwargs
    # print(**m)  # You can't add it here**
test(a=3, b=5, c=7)

Return result:

{'a': 3, 'b': 5, 'c': 7}
<class 'dict'>

The above two indefinite length parameters can be used together, indicating that arbitrary parameters can be accepted. We won't give you examples below. Let's look at the documents. Many built-in methods use this method.

def pow(*args, **kwargs): # real signature unknown
 Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
 Some types, such as ints, are able to use a more efficient algorithm when
 invoked using the three argument form.

Tags: Python

Posted on Sun, 05 Dec 2021 20:16:23 -0500 by Enlightened