"Learn Python with You Hand in Hand" 37-Program Reconstruction

In the previous article "Learning Python with You Hand in Hand" 36-Error and Exception Handling , we learned how to handle errors and exceptions, so that we can face all kinds of uncertain situations gracefully. And make users feel that there is an abnormality in our program.

Error and exception handling is a relatively independent piece of content, and it is also a supplement to the basic Python programming knowledge we introduced before.

At this point, we have completed the introduction of Python basic programming knowledge, and the rest is how we can learn and apply it further.

Today, I will make an application and review of the file operation and exception handling methods learned before. We will use a relatively real example to simulate the application scenario of data storage and reading, and show you how to store data in practical applications. And read how it works.

At the same time, I also borrowed this example to show you the process of program refactoring, that is, how to make the program structure clearer and more readable by reasonably setting functions and optimizing code structure.

1. Application examples of data storage

When we interact with a computer, the computer generally requires us to enter information such as names first, so we design a process of interacting with the computer for the first time. At this time, the computer will ask us to enter our name and record it.

In [1]: import json
        username = input("What's your name?")
        filename = 'username.json'
        with open(filename, 'w') as f:
            json.dump(username, f)
            print("We'll remember you when you come back, {}!".format(username))
Out[1]: What's your name? mnpy
        We'll remember you when you come back, mnpy!

At this point, the data file username.json has stored our user information, you can open the file to have a look. When we enter the program again, the computer will first read the data file and then display the welcome interface.

In [2]: import json
        filename = 'username.json'
        with open(filename) as f:
            username = json.load(f)
            print("Welcome back, {}!".format(username))
Out[2]: Welcome back, mnpy!

Next, we will merge the above two programs. When the user enters, the computer will first determine whether the user information exists, and if it does, it will display the welcome interface; if it does not exist, it will prompt the user to enter the information.

In this code, we will think of the need to use if...else... statements, but for the judgment condition, that is, whether the user information (ie username.json file) exists, if there is, the program can continue to run, if If it does not exist, an error may be reported and the program cannot continue to run.

For this problem, we can use the try...except...else statement in exception and error handling. Even if the file does not exist, the program will not be interrupted due to errors.

In [3]: import json

        filename = 'username.json'
        
        try:
            with open(filename) as f:
                username = json.load(f)
                
        except FileNotFoundError:
            username = input("What's your name?")
            
            filename = 'username.json'
            with open(filename, 'w') as f:
                json.dump(username, f)
                print("We'll remember you when you come back, {}!".format(username))
                
        else:
            print("Welcome back, {}!".format(username))

Run the above program, since we have stored the username.json file before, there will be no exception in the process of opening the file after try, so the running result is:

Out[3]: Welcome back, mnpy!

If we delete the previous username.json file and run this program, because the program after try cannot find the file, it will trigger the file not found error (FileNotFoundError), and then the program after except will be executed and run The result is:

Out[3]: What's your name? mnpy
        We'll remember you when you come back, mnpy!

2. Reconstruction of the program

The above program has actually achieved our expected goal, but it is still not perfect in terms of code writing specifications, structure clarity, and readability (because the program is relatively simple, it is not very obvious).

This process of making the program structure clearer and more readable through a series of structural adjustments or function applications that can already run normally is called reconstruction.

Next, we will optimize the above program and experience the refactoring process together.

In "Learning Python with You" 26-Custom Functions , we mentioned a standardized Python programming structure, which is to put most of the logic or code in the program into one or more functions, and then define the main program Into the main() function, at the same time use a statement such as "if __name__ =='__main__':" to guide the operation of the entire program.

According to this normative structure, the above program can be reconstructed as:

In [4]: import json
        def main():   # 主程序
            
            def greet_user():
                filename = 'username.json'
                
                try:
                    with open(filename) as f:
                        username = json.load(f)
                        
                except FileNotFoundError:
                    username = input("What's your name?")    
                    
                    filename = 'username.json'
                    with open(filename, 'w') as f:
                        json.dump(username, f)
                        print("We'll remember you when you come back, {}!".format(username))
                        
                else:
                    print("Welcome back, {}!".format(username))  
            
            greet_user()
            
        if __name__ == '__main__':
            main()

Although this program implements a standardized program structure and puts the main code in the greet_user() function, it has not been optimized in the greet_user() function. That is to say, in the main() function, there should also be statements composed of functions, instead of the same, the program in a function is still a combination of commands.

In order to achieve this goal, we consider that the entire program's actions are actually three: 1. Let the user input information; 2. Obtain user information; 3. Display the welcome interface.

So next, we will disassemble the original program according to these three actions, and define each action as a function to see the effect of the code reconstruction:

In [5]: """
            程序名称:Welcome back!
            程序作者:mnpy
            程序介绍:用于获取用户信息及展示欢迎界面
            程序版本:2021年1月1日   V1.0
        """
        
        import json
        
        # 主程序
        def main():
            
            # 1、让用户输入信息    
            def get_new_username():
                username = input("What's your name?")
                
                filename = 'username.json'
                with open(filename, 'w') as f:
                    json.dump(username, f)
                
                return username
            
            # 2、获取用户信息      
            def get_stored_username():  
                filename = 'username.json'
                try:
                    with open(filename) as f:
                        username = json.load(f)  
                except FileNotFoundError:  
                    return None
                else:
                    return username
                
            # 3、显示欢迎界面
            def greet_user():
                username = get_stored_username()
                if username:
                    print("Welcome back, {}!".format(username))    
                else:
                    get_new_username()
                    print("We'll remember you when you come back, {}!".format(username))            
            
            # 引导程序启动
            greet_user()
            
        if __name__ == '__main__':
            main()

After refactoring, our code not only satisfies the standardized structural requirements, but in the entire main program, three functions are formed according to the three main actions of the program, and each function can achieve a specific and clear goal. At this time, the structure of the entire program is more clear.

Because our example program is relatively simple overall, the difference may not be obvious. If it is a large program, especially when a program is completed by multiple people, this structured refactoring becomes very important.

The above is a simple summary application of what we have learned before, and we have also experienced the process of program reconstruction through an application example.

So far, the main part of Python basic knowledge is almost introduced. In the next article, we will make a summary of what we have learned before, and use a structured method to sort out and summarize what we have learned at this stage. Stay tuned.

 

 

image

 


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

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

"Learning Python with You Hand in Hand" 28-the return value of a custom function

"Learning Python with You Hand in Hand" 29-Anonymous Functions

"Learning Python with You Hand in Hand" 30-Module

"Learning Python with You Hand in Hand" 31-File Opening

"Learning Python with You Hand in Hand" 32-File Reading

"Learning Python with You Hand in Hand" 33-closing the file

"Learning Python with You Hand in Hand" 34-File Writing

"Learning Python with You Hand in Hand" 35-Data Storage

"Learning Python with You Hand in Hand" 36-Error and Exception Handling

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