leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python knowledge point series (4)

Estimated reading: 14 minutes 62 views

We have learned object-oriented, and now, we will show the application of object-oriented programming through the transcript program.

8, python object-oriented programming

Let’s first analyze, in this program, which places can be represented by classes. Before we used a dictionary to store information about each student, we can now define a Student class to represent students, and use the attributes of this class to represent information such as name, student ID, and grades. We can also use a method of the Student class to calculate and display the total grade, and even use a class method to print students.

Let’s take a look at what properties and methods this class contains. Use the constructor to initialize the property’s value. Attributes include name indicating name, ID indicating student number, score1 indicating Chinese score, score2 indicating math score, score3 indicating English score, and total indicating total score.

Then the getSum() method is defined, which is used to calculate the total score. This method adds up the values ​​of the attributes score1, score2, and score3 representing Chinese grades, math grades, and English grades, and assigns the result to the attribute total.

A printStudent method is also defined, which concatenates the properties into a string and prints it out.

The detailed code of the Student class is shown below.

#Student class to represent students
class Student:
     #Use the constructor to initialize the value of the property
     def __init__(self):
         self.name = ""
         self.ID = ""
         self.score1 = 0
         self.score2 = 0
         self.score3 = 0
         self.total = 0
     #calculate total score
     def getSum(self):
         self.total=self.score1 + self.score2 + self.score3
     # Concatenate the attributes into a string and print it
     def printStudent(self):
         print(self.ID,"\t",self.name,"\t",self.score1,"\t",self.score2,"\t",self.score3,"\t",self.total )

 Below is the rest of the program, where the code involved in calling the Student class is highlighted. Because these codes are basically the same as those used in the previous chapter, they will not be repeated here. Please pay attention to the highlighted part. You can see that the same function can be achieved by calling the method of the class, and the code is more concise and reusable.

#Determine whether the grade list already contains the student number, sList represents the grade list, and sID represents the student number
def hasRecord(sList,sID):
    result=-1
    i = 0
    for temp in sList:
       if temp.ID == sID:
            result=i
            break
       else:
           i=i+1
    return result
#Determine whether the input score is valid, subject represents the subject, and action represents the operation
def getScore(subject, action):
    try:
        score=float(input("Please input"+subject+"score:"))
    except:
        print ("The input is not a number, "+action+" failed!")
        return -1
    if score <= 100 and score >= 0 :
        return score
    else:
        print ("The entered "+subject+" grade is wrong, "+action+" failed!")
        return -1
#Display a list of functions, prompting the user how to select a function
def showInfo():
    print("-"*30)
    print("Student Grade System")
    print("1. Add student information")
    print("2. Delete the student's information")
    print("3. Modify the student's information")
    print("4. Query student information")
    print("5. List all students' information")
    print("6. Exit the system")
    print("-"*30)
def updateStudent(student):
    while True:
        try:
            alterNum=int(input(" 1. Modify name\n 2. Modify student number \n 3. Modify Chinese score \n 4. Modify math score \n 5. Modify English score \n 6. Exit modification\n"))
        except:
            print ("Incorrect input, please enter numbers 1 to 6")
            continue
       if alterNum == 1: #Modify name
            newName=input("Enter the changed name:")
            student.name = newName
            print("Name changed successfully")
            break
        elif alterNum == 2: #Modify student number
            newId=input("Enter the changed student ID:")
            newIndex=hasRecord(studentList, newId)
            if newIndex>-1:
                print("The input student number cannot be repeated, the modification failed!")
            else:
                student.ID=newId
                print("Successfully modified student number")
            break
        elif alterNum == 3: #Modify the language score
            score1=getScore("language","modification")
            if score1 >-1:
                student.score1=score1
                student.getSum()
                print ("Successful revision of Chinese grades!")
            break
        elif alterNum == 4: #Modify math scores
            score2=getScore("Math","Modify")
            if score2 >-1:
                student.score2=score2
                student.getSum()
                print ("The math score has been revised successfully!")
            break
        elif alterNum == 5: #Modify English grades
            score3=getScore("English","Modified")
            if score3 >-1:
                student.score3=score3
                student.getSum()
                print ("The English grade was revised successfully!")
            break
        elif alterNum == 6: #Exit modification
            break
        else: #Incorrect number entered
            print("Input error, please re-enter")
studentList=[]
while True:
    showInfo()
    try:
        key = int(input("Please select the function (input serial number 1 to 6): "))
    except: #If there is an exception, jump out of this loop
        print("Your input is incorrect, please enter the serial number 1 to 6")
        continue
    if key == 1: #Add student information
        print("You have selected the function of adding student information")
        name = input("Please enter your name: ")
        stuId = input("Please enter the student ID (not repeatable):")
        index=hasRecord(studentList,stuId)
        if index >-1:
            print("The input student number is repeated, adding failed!")
            continue
        else:
            newStudent = Student()
            newStudent.name = name
            newStudent.ID = stuId
            score1=getScore("Language","Add")
            if score1 >-1:
                newStudent.score1=score1
            else:
                continue
            score2=getScore("Math","Add")
            if score2 >-1:
                newStudent.score2=score2
            else:
                continue
            score3=getScore("English","Add")
            if score3 >-1:
                newStudent.score3=score3
            else:
                continue
            newStudent.getSum()
            studentList.append(newStudent)
            print (newStudent.name + "Successful entry of grades!")
    elif key == 2: #Delete student information
        print("You have selected the function to delete student information")
        stuId=input("Please enter the student ID to delete:")
        index=hasRecord(studentList,stuId)
        if index>-1:
            del studentList[index]
            print("Deleted successfully!")
        else:
            print("There is no student ID, delete failed!")
    elif key == 3: #Modify student information
        print("You have selected the function of modifying student information")
        stuId=input("Please enter the student ID of the student you want to modify:")
        index=hasRecord(studentList,stuId)
        if index == -1:
            print("Without this student ID, the modification failed!")
        else:
            temp=studentList[index]
            updateStudent(temp)
    elif key == 4: #Query a student's information
        print("You have selected the function of querying student information")
        stuId=input("Please enter the student ID of the student you want to query:")
        index=hasRecord(studentList,stuId)
        if index == -1:
            print("There is no student ID, the query failed!")
        else:
            temp=studentList[index]
            print ("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
            temp.printStudent()
    elif key == 5:
        print("Next to traverse all student information...")
        print("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
        for temp in studentList:
           temp.printStudent()
    elif key == 6:
        quitConfirm = input("Are you sure you want to quit the system (Y or N)?")
        if quitConfirm.upper()=="Y":
            print("Welcome to this system, thank you")
            break
    else: #The number is not entered correctly
        print("You made a mistake, please try again")

9. Open, write and read python files

We have written a program for transcripts earlier, in which the information in the transcripts can only exist when the program is running. When the program is closed, all the information will be lost, which obviously cannot meet the needs of users.

In this case, we can store this information in a text file. In this way, no matter whether the program is closed or not, no data will be lost; and this text file can be copied to any computer, and the student’s information will still exist.

Next, let’s look at the specific implementation method. First, we will create a students.txt text file in the same directory as the “transcript.py” file. Because this text file and the program we are running are in the same directory, we can find this file without specifying a path.

Then, we will add 3 new custom functions: LoadFromText() function that reads data from text, AddToText() function that adds data to text, and WriteToText() function that writes list information to text .

The LoadFromText() function, which reads data from text, accepts a list parameter, and its purpose is to populate the list with the contents of the text file. This function first prints a message to the screen indicating that existing information is to be loaded from the text. Then call the open() function to open the “students.txt” file in read-only mode, and create the file object txtFile.

Then use a while loop with a condition of True, which means that the loop will run all the time until the break statement in the loop is executed to break out of the loop until a specific condition is met.

In the loop, call the readline() function to read a line of text and assign it to the variable line. Then judge whether the line is empty or an empty string. If the condition is met, it means that the end of the file is reached, and the loop is jumped out; otherwise, the split() method is called, with ” ” (two spaces) as the separator, and the result is assigned list s.

Then create an instance stu of the Student class, assign the contents of s to various attributes of stu, and then call the append() function to add the stu instance to the sList list. We covered the split() method earlier when we covered converting between strings and lists. After the while loop ends, call the close() function to close the file.

# Call the data saved in the file
def LoadFromText(sList):
     print("Loading existing data...")
     try:
         txtFile = open("students.txt", "r")
         while True:
             line=txtFile.readline()
             if not line or line.strip()=="" :
                 break
             else:
                 s = line.split(" ")
                 stu = Student()
                 stu.ID = s[0]
                 stu.name = s[1]
                 stu.score1 = float(s[2])
                 stu.score2 = float(s[3])
                 stu.score3 = float(s[4])
                 stu.total = float(s[5])
                 sList.append(stu)
     except: #If student.txt does not exist, create this text file
         txtFile = open("students.txt", "w")
       
     txtFile.close()
     print("Successful loading!")

 The AddToText() function that adds data to the text accepts an instance of the Student class stu as a parameter. First call the open() function to open the “students.txt” file in add mode, and create a file object txtFile. Then write each attribute value of stu into the text object, and put two spaces between each attribute as a space. A “\n” is added at the end to indicate a newline. Finally, call the close() function to close the file.

#Add a piece of data to the file
def AddToText(stu):
    txtFile = open("students.txt", "a")
    txtFile.write(stu.ID)
    txtFile.write(" ")
    txtFile.write(stu.name)
    txtFile.write(" ")
    txtFile.write(str(stu.score1))
    txtFile.write(" ")
    txtFile.write(str(stu.score2))
    txtFile.write(" ")
    txtFile.write(str(stu.score3))
    txtFile.write(" ")
    txtFile.write(str(stu.total))
    txtFile.write("\n")
    txtFile.close()

The WriteToText() function that writes data to text accepts a list parameter, and its purpose is to write the data in the list to a text file. First call the open() function to open the “students.txt” file in write mode and create the file object txtFile.

Then use a for loop to traverse the elements in the sList list, assigning each element to an instance of the Student class, stu. Then write each attribute value of stu into the text, and put two spaces between each attribute as space. A “\n” is added at the end to indicate a newline. After the loop is over, call the close() function to close the file.

#Save all the data in the list to a file
def WriteToText(sList):
    txtFile = open("students.txt", "w")
    for stu in sList:       
        txtFile.write(stu.ID)
        txtFile.write(" ")
        txtFile.write(stu.name)
        txtFile.write(" ")
        txtFile.write(str(stu.score1))
        txtFile.write(" ")
        txtFile.write(str(stu.score2))
        txtFile.write(" ")
        txtFile.write(str(stu.score3))
        txtFile.write(" ")
        txtFile.write(str(stu.total))
        txtFile.write("\n")
    txtFile.close()

Below is the rest of the program, and we’ve highlighted the code involved in calling these 3 functions. Because other codes are basically the same as those in the previous section, they will not be repeated here.

#define the Student class to represent students
class Student:
    #Use the constructor to initialize the value of the property
    def __init__(self):
        self.name = ""
        self.ID = ""
        self.score1 = 0
        self.score2 = 0
        self.score3 = 0
        self.total = 0
    #calculate total score
    def getSum(self):
        self.total=self.score1 + self.score2 + self.score3
    # Concatenate the attributes into a string and print it
    def printStudent(self):
        print(self.ID,"\t",self.name,"\t",self.score1,"\t",self.score2,"\t",self.score3,"\t",self.total )
#Determine whether the grade list already contains the student number, sList represents the grade list, and sID represents the student number
def hasRecord(sList,sID):
    result=-1
    i = 0
    for temp in sList:
        if temp.ID == sID:
             result=i
             break
        else:
            i=i+1
    return result
#Determine whether the input score is valid, subject represents the subject, and action represents the operation
def getScore(subject, action):
    try:
      score=float(input("Please input"+subject+"score:"))
    except:
        print ("The input is not a number, "+action+" failed!")
        return -1
    if score <= 100 and score >= 0 :
        return score
    else:
        print ("The entered "+subject+" grade is wrong, "+action+" failed!")
        return -1
#Display a list of functions, prompting the user how to select a function
def showInfo():
    print("-"*30)
    print("Student Grade System")
    print("1. Add student information")
    print("2. Delete the student's information")
    print("3. Modify the student's information")
    print("4. Query student information")
    print("5. List all students' information")
    print("6. Exit the system")
    print("-"*30)
def updateStudent(sList,student):
    while True:
        try:
            alterNum=int(input(" 1. Modify name\n 2. Modify student number \n 3. Modify Chinese score \n 4. Modify math score \n 5. Modify English score \n 6. Exit modification\n"))
        except:
            print ("Incorrect input, please enter numbers 1 to 6")
        continue
        if alterNum == 1: #Modify name
            newName=input("Enter the changed name:")
            student.name = newName
            print("Name changed successfully")
            break
        elif alterNum == 2: #Modify student number
            newId=input("Enter the changed student ID:")
            newIndex=hasRecord(sList, newId)
            if newIndex>-1:
                print("The input student number cannot be repeated, the modification failed!")
            else:
                student.ID=newId
                print("Successfully modified student number")
            break
        elif alterNum == 3: #Modify the language score
            score1=getScore("language","modification")
            if score1 >-1:
                student.score1=score1
                student.getSum()
                print ("Successful revision of Chinese grades!")
            break
        elif alterNum == 4: #Modify math scores
            score2=getScore("Math","Modify")
            if score2 >-1:
                student.score2=score2
                student.getSum()
                print ("The math score has been revised successfully!")
            break
        elif alterNum == 5: #Modify English grades
            score3=getScore("English","Modified")
            if score3 >-1:
                student.score3=score3
                student.getSum()
                print ("The English grade was revised successfully!")
            break
        elif alterNum == 6: #Exit modification
            break
        else: #Incorrect number entered
            print("Input error, please re-enter")
    WriteToText(sList)
studentList=[]
LoadFromText(studentList)
while True:
    showInfo()
    try:
        key = int(input("Please select the function (input serial number 1 to 6): "))
    except: #If there is an exception, jump out of this loop
        print("Your input is incorrect, please enter the serial number 1 to 6")
        continue
    if key == 1: #Add student information
        print("You have selected the function of adding student information")
        name = input("Please enter your name: ")
        stuId = input("Please enter the student ID (not repeatable):")
        index=hasRecord(studentList,stuId)
        if index >-1:
            print("The input student number is repeated, adding failed!")
            continue
        else:
            newStudent = Student()
            newStudent.name = name
            newStudent.ID = stuId
            score1=getScore("Language","Add")
            if score1 >-1:
                newStudent.score1=score1
            else:
                continue
            score2=getScore("Math","Add")
            if score2 >-1:
                newStudent.score2=score2
            else:
                continue
            score3=getScore("English","Add")
            if score3 >-1:
                newStudent.score3=score3
            else:
                continue
            newStudent.getSum()
            studentList.append(newStudent)
            AddToText(newStudent)
            print (newStudent.name + "Successful entry of grades!")
    elif key == 2: #Delete student information
        print("You have selected the function to delete student information")
        stuId=input("Please enter the student ID to delete:")
        index=hasRecord(studentList,stuId)
        if index>-1:
            del studentList[index]
            WriteToText(studentList)
            print("Deleted successfully!")
        else:
            print("There is no student ID, delete failed!")
    elif key == 3: #Modify student information
        print("You have selected the function of modifying student information")
        stuId=input("Please enter the student ID of the student you want to modify:")
        index=hasRecord(studentList,stuId)
        if index == -1:
            print("Without this student ID, the modification failed!")
        else:
            temp=studentList[index]
            updateStudent(studentList,temp)
    elif key == 4: #Query a student's information
        print("You have selected the function of querying student information")
        stuId=input("Please enter the student ID of the student you want to query:")
        index=hasRecord(studentList,stuId)
        if index == -1:
            print("There is no student ID, the query failed!")
        else

After entering the student’s information, even if the program is closed, you can see the entered information in the “students.txt” file, as shown in the following figure.

Python file opening, reading and writing

 At this point, we have completed some knowledge points that can be linked in a series of transcripts. If we have not reviewed them, we have to read them by ourselves.

Leave a Comment

CONTENTS