python basic syntax 002 function_ Two articles take you through (Part 2)

🐚 About the author: Su Liang (focusing on web crawler and data analysis)
🐳 Blog home page: Su Liang py blog
👑 Famous aphorism: the sea is wide with fish jumping, and the sky is high with birds flying.
📰 If you think the blogger's article is good, I hope you can support it three times in a row!!!
👉 follow ✨ give the thumbs-up 👍 Collection 📂

🍺 preface

In the last article, we learned about what is a function, function call, function return value, function parameters, and function variable scope. Today, let's take you to a more in-depth study of functions. In the next article, I will summarize the functions and syntax of all built-in functions in Python. Please look forward to it. Let's get to the point directly below!
🚀 Previous delivery anchor: python basic syntax 001 - functions_ Two articles take you through (Part I)
💠 For a review of previous issues, please see the column:
python crawler from 0 to 1
Fundamentals of python data analysis

🔆 Parameter extension

🛸 Keyword parameters

When calling a function, the order of the incoming data is the order of the parameters defined by us. If we want to transfer values not in order, we can use keyword parameters to transfer values.

def list(x,y,z):

list(6,7,5) #Transfer values in sequence
list(z = 5,x = 6,y = 7) #Using keyword parameters to transfer values in random order


Note: if the first value is transferred by keyword parameter, the subsequent value must also be transferred by keyword parameter.

🛸 Default value parameter

When we define a function, we can set the default value of parameters. At this time, when we call the function, when there is no incoming data, the default value will be displayed.

def list(name,age="unknown"):

list('Su Liang',21)


Here you can see that if we set the default value of the parameter, there will be no error even if we do not pass in the parameter!!

Note: when setting default values for parameters, you can only set them from back to front!!

🛸 Formal and argument

Formal parameter - formal parameter, which is the parameter passed in when defining the function.
Argument - actual parameter, the parameter passed in when calling the function. At this time, when passing parameters, the formal parameters will be assigned with actual parameters.

def list(a):
    a  = a+1
x = 5
list(x) #Result: 6
print(x) #Result: 5

In the above example, a is the formal parameter and x is the actual parameter.
Think: why assign the value of x to a, and the value of x printed at the end of the result is still 5, which has not changed?

If the parameter defined in the function is given a value, the variable outside the function cannot be changed. When the parameter is not assigned in the function, the value of the variable outside the function can be changed.

def list(a):

x = [0, 1, 2, 3]

At this point, you can see that the parameter is not assigned in the function body, so the x outside the function can be modified.

🔆 Variable parameter

When defining a function without knowing how many parameters we need to pass when we finally call the function, we can use variable parameters to define the function. At this time, we can pass any number of values when we call the function.
Note: only one variable parameter can exist in a function!

When defining a function, define a variable parameter starting with *.
In the function body, the variable parameter args saves all the parameters. The type is tuple!!

def list(*args):

#Results: (1, 2, 3, 4)

When the function is called later, no matter how many values are passed in, they can be printed out.

When variable parameters are used with normal parameters:

def list(a ,b ,*args,c,d):



Note: values must be assigned in sequence before variable parameters. Keyword parameters cannot be used to transfer values. After variable parameters, keyword parameters must be used to transfer values!! Otherwise, the following values are the values of variable parameters by default!

🔆 Variable keyword parameters

As mentioned above, variable parameters cannot be assigned by private keyword parameters when calling functions, and they return a tuple type.
Variable keyword parameters must use keyword parameters to pass values, and return a dictionary type.
Used to represent variable keyword parameters when defining functions**

def list(**kwargs):
    for k ,v in kwargs.items():

list(a =1 ,b = 2, c = 3)


Note: variable keyword parameters can only be placed last when used with other parameters!!

def list(a,b,**kwargs):
    # for k ,v in kwargs.items():
    #     print(f'{k}:{v}')

list(a =1 ,b = 2,x = 5 ,y = 6 )


🔆 Tuple unpacking

In python, * means any number. This can be used to split the elements in the tuple, which is what we call tuple unpacking!! Any iteratable object can be unpacked!

name,age,QQ_num,*others,c = ('Su Liang','21','787991021',4,5,6,7)
print(name, age, QQ_num,*others,c)
 # ==============================
def list():
    return 'Su Liang','21','787991021',4,5,6,7
name,age,QQ_num,*others,c =list()
print(name, age, QQ_num,*others,c)

Note: when unpacking, there can only be one * parameter. When it is used with common parameters at the same time, the common parameters shall be assigned first, and the last remaining values shall be assigned to the defined * parameter

Unpack the dictionary

a , b ,*c = {'name':"Su Liang",'age':21,'QQ_num':'787991021','other':'none'}.items()


It can be seen that the object returned by unpacking the dictionary is of tuple type. When unpacking the dictionary, the key of the dictionary is unpacked by default. If you want to unpack the value, add Values method. If you want to unpack all key values, add The items() method.

🔆 Function type parameters

Functions can also be used as parameters! Let's look at a simple example.

def list1(num1,num2):
def list2():
    print('Execution complete!')



Here, when calling the function list1, pass the function list2 as a parameter to num2. Finally, when executing the function list1, execute list2.

🔆 Higher order function

For nested functions, the return values of functions are called higher-order functions

🛸 Nested function

def list1():
    def list2():



Note: any variables defined in the function and nested functions can only be used in the function! That is, in the above example, list2() cannot be called directly outside the function

🛸 Function return value

Let's use a small case to illustrate: guess the number three times!!

count = 0
while True:
    count = count +1
    if count>3:
    def list1(num):
        def list2():
            nonlocal num
            if num>5:
                return 'Bigger than this number!!'
            elif num==5:
                return 'You guessed right!!'
            return 'Smaller than this number!!'
        return list2

    i= int(input('Enter integer:'))
    a = list1(i)


In the middle note base note, nonlocal declares the local variable. When calling the function list1, function list1 returns list2, so the value of list2 is assigned to a, and finally calls a(), that is, calling list2() in list1.

The above operations are also called closure operations. The detailed explanation also depends on the subsequent content output, which will not be repeated here.

🔆 Anonymous function

Some functions don't have anonymous names

🛸 lambda syntax

In python, lanbda is used to implement anonymous functions!
lambda is also a function with return value and parameters, but no name.

def f(x):
    return x*10

a = lambda x:x*10



Here you can see that the two effects are the same.
Note: you cannot wrap lines in lambda syntax, that is, you can only define some simple methods or expressions. In addition, lambda can also contain multiple parameters.

🔆 Recursive function

The method of calling the function itself in the function body is called recursion.

Example: use recursive function to realize the factorial of numbers!

def list1(i):
    if i<=1:
        return 1
        return list1(i-1)*i

b = list1(5)


In python, the number of cycles of a recursive function is limited, not infinite!!

🍻 epilogue

See here, I believe everyone has a certain understanding of functions. The next step is to constantly optimize its understanding in actual combat. Well, that's all about the function. If you want to add something, you can discuss it in the comment area or chat privately. I can also! The next article mainly summarizes the use of built-in functions in python. Pay attention to me. See you next time!

Tags: Python function

Posted by Haroskyline on Mon, 18 Apr 2022 09:30:56 +0930