Python Level 2 Comprehensive Application Questions: Address Book Management

The last question in the Python Level 2 exam is generally the final question, which is difficult and has a high score. This question is generally divided into 1~3 questions, and only by winning every step can we solve it better. When encountering this kind of problem, first of all, don't be afraid, it takes a few steps to solve it. Today we have an address book management question to explain:

1. Topics

Use dictionaries and lists to complete the management of student address books. The list is given by the file address.txt, and each line is a student's information. Examples are as follows:

学号,姓名,电话号码,地址
101,aa,12345678,Beijing
102,bb,23456781,shanghai
...(略)

Question 1: Modify P301-1.py to display the function menu on the screen. The example of the function menu is as follows:

1. 显示所有信息
2. 追加信息
3. 删除信息
请输入数字 1-3 选择功能:

Please enter the number 1-3 selection function ( requirement: no floating-point number input is allowed ): accept the user input number selection function, if the input is wrong, the user is required to re-input. If the input is correct, the prompt statement will be displayed on the screen: 您选择了功能1/2/3. (5 points)

Question 2: Modify P301-2.py . Based on the code in question 1, when the user selects 1, read information from the address book file and display all the information. (5 points) An example is as follows:

1. 显示所有信息
2. 追加信息
3. 删除信息
请输入数字1-3选择功能:1
101,aa,12345678,Beijing
102,bb,23456781,shanghai
...(略)

Question 3: Modify P301-3.py  . Based on the code in question 2, when the user selects 2, let the user enter a student's information from the keyboard, separated by commas. Write the information to the file new_address.txt, the file format is the same as address.txt. (10 points) The content example of new_address.txt is as follows:

101,aa,12345678,Beijing
102,bb,23456781,shanghai
103,cc,34567,tianj

Example 1 :

输入: "1"
     "1"
     "2"
     "103,cc,34567,tianj"
输出: 内容输出到 new_address.txt 文件中

2. Solution steps

1. Solution to Problem 1

Example:

menu=["1. 显示所有信息","2. 追加信息","3. 删除信息"]
...
        ch = int(input("请输入数字1-3选择功能:") )
...
print("您选择了功能", ch)

Solution: Use flag to define a switch, when its value is 1, it means on, and when it is 0, it means off.

menu = ["1.显示所有信息","2.追加信息","3.删除信息"]
flag = 1
while flag:
    for m in menu:
        print(m)
    try:
        num = int(input("请输入数字1-3选择功能:")) #将获取的字符型数字转化为数字
        if num ==1:
            flag = 0
    except:
        flag = 1
        
    if num<1 or num >3:
        flag = 1

The above is looped through while. When the specified flag is 1, the program continues to loop. When the flag is 0, the program stops running. Use try...except to catch exceptions, and use if to judge the size of num.

2. Solution to problem 2

On the basis of question 1, a function of printing all address books is added. We can define a function called display that is called when 1 is entered. Note that the function should be written in front of the while loop, otherwise it cannot be called.

def display():
    with open("address.txt",'r',encoding='utf-8') as f:
        for fi in f:
            print(fi,end="")

Original code:

def display():
    fi = open("address.txt", 'r')
    for line in fi:
        print(line,end="")
    fi.close()
    
menu = ["1. 显示所有信息", "2. 追加信息", "3. 删除信息"]
flag = 1
while flag:
    
    for m in menu:
        print(m)
        flag = 0
    try:
        print("请输入数字1-3选择功能:")
        ch = int(input())
        flag = 0
    except:
        flag = 1
    if flag <1 or flag >3:
        flag = 1
    elif ch == 1:
        display ()

In the official code, the final if judgment is written outside the while loop, but it should be written inside after testing, as shown in the following figure:

3. Solution to Problem 3

We also need to define another insertion function, which accepts the characters input on the screen and appends them to the list with append, and then writes them into new_address.txt with a for loop.

def display():
    fi = open("address.txt", 'r')
    for line in fi:
        print(line,end="")
    fi.close()

def insertrec(text):
    with open("address.txt",'r',encoding='utf-8') as file:
        newline = file.readlines()
        newline.append(text+"\n")
        with open("new_address.txt","w+",encoding='utf-8') as newfile:
            for line in newline:
                newfile.write(line)    

menu = ["1. 显示所有信息", "2. 追加信息", "3. 删除信息"]
flag = 1
while flag:
    for m in menu:
        print(m)
        flag = 0
    try:
        print("请输入数字1-3选择功能:")
        ch = int(input())
        flag = 0
    except:
        flag = 1
    if flag <1 or flag >3:
        flag = 1
    elif ch == 1:
        display ()
    elif ch == 2:
        insertrec()

The above code uses the code written by myself, the following is the official code:

def insertrec():
   fi = open("address.txt",'r')
   fo = open("new_address.txt",'w')
   la=[]
   for l in fi:
       la.append(l.replace('\n',''))
   print("请输入要插入的信息,以逗号隔开,示例:103, cc, 34567812, tianjing:")
   rec = input()
   la.append(rec)
   for l in la:
       fo.write(l)
       fo.write('\n')
   fi.close()
   fo.close()

The way to write fo in the official code should be w+, if it is w, an error will be reported if the file does not exist. la.append(l.replace('\n','')) This step seems useless. I only need to add a [\n] when appending, and then use write to write directly. The newline itself comes with itself, so there is no need to toss.

3. Post-school reflection

  1. The official solution requires a deep understanding of its principles, and the algorithm can be further optimized and improved on the basis of understanding.
  2. There are many ways to deal with \n, such as str.strip() can remove newlines, use print(string,end="\n") to add newlines, and so on.

Guess you like

Origin blog.csdn.net/henanlion/article/details/131274206