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

In the last article "Learning Python with You" 25-List Comprehension , we learned the related concepts and usage of deduction. Using deduction methods can reduce the amount of code input and improve readability. A very popular form in Python.

Starting today, we will learn the most important and basic form of code organization and code reuse in Python-functions.

The functions here include not only functions that we have learned before and have been defined in Python, or built-in functions, but also functions that we define ourselves to achieve our desired functions, that is, custom functions. Unless otherwise specified, the functions mentioned later generally refer to custom functions.

According to experience, if you need to repeat the same or similar code multiple times, it is worth writing a reusable function. By defining a name for a group of Python statements to form a function, we can better organize our code and improve readability.

So when do you need a custom function, what do you mean by code organization and code reuse?

Let us first take a small example to see how the function achieves code organization and code reuse.

Because this example is only used to show the function of the function, it may not be very rigorous in terms of code writing. For some places that are not considered comprehensive or may report errors, please ignore it for the time being. If you are interested, I suggest that you also write this program yourself, which is also an opportunity to review what we have learned and practice in the past.

1. Programming examples without using custom functions

Suppose there are two children, A and B, throwing dice, and each child throws three times, and the one with the largest number of dice throws three times shall prevail. The bigger one wins.

According to the method we learned before, we can write the following program:

In [1]: import random
​
        A = []
        for i in range(3):
            result = random.randrange(1, 7)
            A.append(result)
        A_result = max(A)
        
        B = []
        for i in range(3):
            result = random.randrange(1, 7)
            B.append(result)
        B_result = max(B)
        
        if A_result > B_result:
            print("胜利者是A。")
        elif A_result < B_result:
            print("胜利者是B。")
        else:
            print("双方打平。")
            
Out[1]: 双方打平。

Because this program is relatively simple and the structure is not complicated, it will not be difficult for everyone to read it. But even so, if we carefully observe the program, there are areas that can be optimized.

The easiest thing to see is that the procedures to get the dice results of the two children A and B are almost the same, but we use different variable names.

In addition, although the final if-else structure conforms to the grammatical rules, the multi-level nesting is still a bit cumbersome. It would be nice if it could be expressed in a more concise code.

The two points mentioned above may not be handled well with our existing knowledge, although other methods can also be used to achieve them, but they cannot achieve obvious optimization effects.

So, let our function come out now and see how the custom function achieves code optimization. Because in this part, we are just to explain how custom functions implement code organization and code reuse, so you don’t need to pay attention to the syntax of the code.

2. Programming examples using custom functions

In [2]: import random
​
        def play():
            kid = []
            for i in range(3):
                result = random.randrange(1,7)
                kid.append(result)
            kid_result = max(kid)
            return kid_result
                        
        def win(A, B):
            if A > B:
                winner = "胜利者是A。"
            elif A < B:
                winner = "胜利者是B。"
            else:
                winner = "双方打平。"
            return winner
            
        A = play()
        B = play()
        print(win(A, B))
        
Out[2]: 胜利者是B。

The above is the program code we wrote using custom functions. Although in terms of the amount of code, you may not think there is any simplification (both are 18 lines), but the main program of the program that uses a custom function actually only has the last three lines (A = play(); B = play(); print(win(A, B))) and other parts (beginning with def and ending by return) are all part of our custom function.

In this example, we define two functions-play() and win(), whose functions are to calculate the results of children throwing objects and determine the results of the game.

Therefore, on the one hand, there is no repeated code in the optimized program, and code reuse is realized by using custom functions; on the other hand, in the optimized program, the final result is achieved by using only one statement. The output of the code, that is, the organization of the code is optimized.

Seeing this, some friends may say that although only one sentence is used to output the result, the complex statement of if-else structure is also used in the function, which is not simplified than the original code?

This is a very good question, but also the most valuable part of custom functions. By customizing functions, you can optimize the repetitive, complex, and unclear parts of the original program to avoid code duplication, or define complex code blocks as functions to make the structure of the main program clearer.

Therefore, although our new code does not have fewer lines than the original code, we use custom functions to avoid the appearance of duplicate code, while simplifying the main program code, making its structure clearer, and easier to read and understand.

Because our example is very simple, if it is a very complex example or project, using a custom function to write, the room for simplification and optimization is very large, not just the difference we see now.

In addition, there are built-in functions that we often use, which are actually custom functions written by Python developers. We call them very convenient and concise. It is hard to imagine if these built-in functions also require us to write the complete code in the program.

So, as we said at the beginning of this article, custom functions are the most basic programming method in Python. Next, we will begin the specific explanation of the custom function, and everyone can gradually realize the power of the custom function.

3. The grammatical form of the custom function

In the above example, we have seen that a custom function is a code block beginning with the keyword def and ending with the keyword return. The process of writing a custom function is called a function declaration, and the process of using a custom function in the main program is called a function call. A typical function is composed of the following structure:

def 函数名称(参数列表):
    函数体
    return 变量名

Among them, according to the needs of the custom function, the parameter list can be omitted, just write a parenthesis, just like the play() function in our example just now. It can also include one or more parameters, just like the win(A, B) function in our example. The specific explanation of the function parameters will be introduced in the next article.

Functions generally end with a return statement, which is used to exit the function and return the result of the function. In a function, there can be multiple return statements, or return can be omitted, and None will be returned automatically, just like the simple program below.

In [3]: def hello():
            print("这个函数的作用就是打印这句话,不需要有什么返回值。")
            
        print("下面开始运行hello()函数:")
        hello()
        
Out[3]: 下面开始运行hello()函数:
        这个函数的作用就是打印这句话,不需要有什么返回值。

If you add parameters to the hello() function, you can print the contents of any passed function in a custom form.

In [4]: def hello(text):
            print("这个函数的作用就是打印传入函数的这句话:", text)
            
        a = "打印我吧!"
        hello(a)
        
Out[4]: 这个函数的作用就是打印传入函数的这句话:
        打印我吧!

In the above example, we can also see that the variable name of the input function and the variable name of the defined function can be different, and the specific explanation is also in the next article.

Finally, I will introduce you to a standardized Python programming structure. In addition to the def...return... that we just used when customizing the function to declare the function, we also need to define the main program as a main() function, and use a statement such as "if __name__ ='__main__'" to guide the whole The operation of the program. Therefore, the dice-throwing program we wrote before can be written as this kind of normative Python statement.

import random
​
def play():
    kid = []
    for i in range(3):
        result = random.randrange(1,7)
        kid.append(result)
    kid_result = max(kid)
    return kid_result
        
def win(A, B):
    if A > B:
        winner = "胜利者是A。"
    elif A < B:
        winner = "胜利者是B。"
    else:
        winner = "双方打平。"
    return winner
        
def main():
    A = play()
    B = play()
    print(win(A, B))
        
if __name__ == '__main__':
    main()

In this structure, we actually define the main program as the main() function, because "if __name__ =='__main__':" is always true, so the main() function must also run.

The reason why the Python program is written in such a structure is mainly to prevent other programs from running directly when calling the script. The specific explanation may be more complicated. You can ignore it for the time being. You only need to make good use of this standardized Python when writing programs in the future. The structure is fine.

In this article, we mainly introduce the basic concepts and grammatical format of custom functions, and illustrate the role of custom functions through a few small examples. In the next article, we will give a detailed introduction to the declaration, parameters and return value of the custom function, 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

For Fans: Follow the "also said Python" public account, reply "hand 26", 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/103895537