Python knowledge point series (3)
In the process of software development, there will be exceptions during the operation of the program. We can use the function of exception handling to make the transcript program more robust, so as not to terminate the program easily.
6. Python exceptions and comments
We will focus on monitoring and testing the content entered by the user. Even if the user enters the wrong content, the program will make corresponding prompts and will not end. For example, if the user selects a function that is not a number, it will prompt for a typo. When inputting the language score, we will add an exception judgment to the statement float(input(“Please input the language score: “)). If there is an exception, it means that the input is not a number, and a corresponding prompt will be given instead of Let the program report an error and terminate directly.
In addition, we have annotated the program to make it easier to read and understand. At the beginning of the program, the author of the program, the date of completion and other information are explained through comments. And the comments inside the program make the program easier to understand. The complete code is shown below.
"""
Program: Transcript V
Author: Li Qiang
Date written: July 1, 2019
"""
studentList=[] #Record the list of student information
while True:
#Display a list of functions, prompting the user how to select a function
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)
try:
key = int(input("Please select the function (input serial number 1 to 6): "))
except: #If an exception occurs, jump out of this loop and no longer execute the following code
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):")
hasRecord = False
for temp in studentList:
if temp["ID"] == stuId:
hasRecord = True
break
if hasRecord == True:
print("The input student number is repeated, adding failed!")
continue
else:
student = {}
student["name"] = name
student["ID"] = stuId
try:
score1=float(input("Please enter the language score:"))
except:
print ("The input is not a number, adding failed!")
continue
if score1 <= 100 and score1 >= 0 :
student["score1"]=score1
else:
print ("The input language score is wrong, adding failed!")
continue
try:
score2=float(input("Please enter math score:"))
except:
print ("The input is not a number, adding failed!")
continue
if score2 <= 100 and score2 >= 0 :
student["score2"]=score2
else:
print ("The entered math score is incorrect, adding failed!")
continue
try:
score3=float(input("Please input English score:"))
except:
print ("The input is not a number, adding failed!")
continue
if score3 <= 100 and score3 >= 0 :
student["score3"]=score3
else:
print ("The English grade entered is incorrect, adding failed!")
continue
student["total"]=student["score1"] + student["score2"] + student["score3"]
studentList.append(student)
print (student["name"]+"'s grades are successfully entered!")
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:")
i = 0
hasRecord = False
for temp in studentList:
if temp["ID"] == stuId:
hasRecord = True
break
else:
i=i+1
if hasRecord == True:
del studentList[i]
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:")
hasRecord = False
for temp in studentList:
if temp["ID"] == stuId:
hasRecord = True
break
if hasRecord == False:
print("Without this student ID, the modification failed!")
else:
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:
newName=input("Please enter the changed name:")
temp["name"] = newName
print("Name changed successfully")
break
elif alterNum == 2:
newId=input("Please enter the changed student ID:")
hasSameID = False
for temp1 in studentList:
if temp1["ID"] == newId:
hasSameID = True
break
if hasSameID == True:
print("The input student number cannot be repeated, the modification failed!")
else:
temp["ID"]=newId
print("Successfully modified student number")
break
elif alterNum == 3:
try:
score1=float(input("Please input the changed language score:"))
except:
print ("The input is not a number, the modification failed!")
break
if score1 <= 100 and score1 >= 0 :
temp["score1"]=score1
temp["total"]=temp["score1"] + temp["score2"] + temp ["score3"]
print ("Successful revision of Chinese grades!")
else:
print ("The input language score is wrong, the modification failed!")
break
elif alterNum == 4:
try:
score2=float(input("Please enter the changed math score:"))
except:
print ("The input is not a number, the modification failed!")
break
if score2 <= 100 and score2 >= 0 :
temp["score2"]=score2
temp["total"]=temp["score1"] + temp["score2"] + temp ["score3"]
print ("The math score has been revised successfully!")
else:
print ("The input math score is wrong, the modification failed!")
break
elif alterNum == 5:
try:
score3=float(input("Please enter the changed English score:"))
except:
print ("The input is not a number, the modification failed!")
break
if score3 <= 100 and score3 >= 0 :
temp["score3"]=score3
temp["total"]=temp["score1"] + temp["score2"] + temp ["score3"]
print ("The English grade was revised successfully!")
else:
print ("The entered English grade is wrong, the modification failed!")
break
elif alterNum == 6:
break
else:
print("Input error, please re-enter")
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:")
hasRecord = False
for temp in studentList:
if temp["ID"] == stuId:
hasRecord = True
break
if hasRecord == False:
print("There is no student ID, the query failed!")
else:
print ("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t", temp["score3"],"\t",temp["total"])
elif key == 5: #Print out the information of all students
print("Next to traverse all student information...")
print("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
for temp in studentList:
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t", temp["score3"],"\t",temp["total"])
elif key == 6: # opt out of the system
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")
7. Python custom function
Let’s further improve the transcript program with the custom function we learned earlier. The complete code is shown below.
"""
Procedure: Transcript VI
Author: Li Qiang
Date written: July 2, 2019
"""
#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 grade 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("7. Sort")
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 7. Sort \n"))
except:
print ("Incorrect input, please enter numbers 1 to 7")
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["total"]=student["score1"] + student["score2"] + student["score3"]
print ("Successful revision of Chinese grades!")
break
elif alterNum == 4: #Modify math scores
score2=getScore("Math","Modify")
if score2 >-1:
student["score2"]=score2
student["total"]=student["score1"] + student["score2"] + student["score3"]
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["total"]=student["score1"] + student["score2"] + student["score3"]
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 an exception occurs, jump out of this loop, no longer execute the following code, but ask the user to re-enter
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:
student = {}
student["name"] = name
student["ID"] = stuId
score1=getScore("Language","Add")
if score1 >-1:
student["score1"]=score1
else:
continue
score2=getScore("Math","Add")
if score2 >-1:
student["score2"]=score2
else:
continue
score3=getScore("English","Add")
if score3 >-1:
student["score3"]=score3
else:
continue
student["total"]=student["score1"] + student["score2"] + student["score3"]
studentList.append(student)
print (student["name"]+"'s grades are successfully entered!")
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")
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t", temp["score3"],"\t",temp["total"])
elif key == 5: #Print out the information of all students
print("Next to traverse all student information...")
print("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
for temp in studentList:
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t", temp["score3"],"\t",temp["total"])
elif key == 6: # opt out of the system
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")
First, you can place reused code in custom functions so you don’t have to repeatedly copy and paste code. In the code introduced above, whether it is selecting query and adding, or modifying and deleting, it is necessary to first determine whether the current list already contains the entered student ID. Therefore, the code for judging whether the specified student number is included in the list can be used as a custom function, taking the list and the specified student number as parameters, and returning a result value to indicate whether the corresponding student number is found in the list. element.
Let’s take a look at the specific code. We define a function named hasRecord to determine whether the existing elements in the list contain the specified student number. This function has two formal parameters, one is sList representing the list, and the other is the specified student ID sID.
A variable result is defined in the function, which will be the return value of the function. Initially, the variable result is set to −1, indicating that no corresponding element has been found so far. Then a temporary variable i is created, with an initial value of 0, which corresponds to the index value of the current element in the for loop. Then use a for loop to traverse each element in the sList list and assign each element to the variable temp.
In each iteration, it is determined whether the value corresponding to the key “ID” of temp is equal to the parameter sID. If they are equal, it means that there is an element with the same student number in the list, and the value of the variable i will be assigned to result, so that the value of result is the index corresponding to the element, and then call the break statement to jump out of the for loop; if not equal , add 1 to the variable i, enter the next iteration, and judge the next element.
After the for loop is executed, use the keyword return to return the result to the function call. The function that calls it can know whether there is a corresponding element by judging whether the return value is equal to −1. If it is equal to −1, it means that there is no corresponding element. If it is equal to other values, it means that the corresponding element is found and the index of the element is the return value of the function.
#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
You can also put the code that is used repeatedly to judge whether the input grade is valid or not into a custom function. Here, this custom function is named getScore, and two formal parameters are specified for it, one is the subject representing the subject, and the other is the action representing the action, both of which are strings.
First, use the formal parameter subject and other strings to form a sentence. For example, if the formal parameter is “language”, it can be spelled as “please enter the language score:”. Then convert the content entered by the user into a floating point number and save it to the variable score.
Then judge whether the variable score is between 0 and 100. If it is within this range, it means that the score is a valid number, and use the keyword return to directly return it to the function call. If it is not in this range, the user is prompted for an input error and −1 is returned to the function call. The function that calls it can know whether the input value is valid as long as the return value is equal to −1.
#Determine whether the input grade 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
Another role of custom functions is to hide large pieces of code into functions and give them an easy-to-understand name, so that the code can be better planned and organized, so that the core code looks more concise and clear. Here, we can put the code that displays the list of functions into a custom function called showInfo. This function has no parameters and no return value, it just calls the print function to print the prompt information to the screen.
#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)
You can also put the large piece of code that modifies the student information into the custom function updateStudent, and specify the formal parameter student representing the student information for the function, which also has no return value. The content of the code has been introduced above and will not be repeated here.
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["total"]=student["score1"] + student["score2"] + student["score3"]
print ("Successful revision of Chinese grades!")
break
elif alterNum == 4: #Modify math scores
score2=getScore("Math","Modify")
if score2 >-1:
student["score2"]=score2
student["total"]=student["score1"] + student["score2"] + student["score3"]
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["total"]=student["score1"] + student["score2"] + student["score3"]
print ("The English grade was revised successfully!")
break
elif alterNum == 6: #Exit modification
break
else: #Incorrect number entered
print("Input error, please re-enter")
Next, you can call these functions in the program, obviously the code here looks much cleaner than the previous code that implements the same function. The lines of code highlighted here represent function calls.
studentList=[]
while True:
showInfo()
try:
key = int(input("Please select the function (input serial number 1 to 6): "))
except: #If an exception occurs, jump out of this loop, no longer execute the following code, and ask the user to re-enter
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:
student = {}
student["name"] = name
student["ID"] = stuId
score1=getScore("Language","Add")
if score1 >-1:
student["score1"]=score1
else:
continue
score2=getScore("Math","Add")
if score2 >-1:
student["score2"]=score2
else:
continue
score3=getScore("English","Add")
if score3 >-1:
student["score3"]=score3
else:
continue
student["total"]=student["score1"] + student["score2"] + student["score3"]
studentList.append(student)
print (student["name"]+"'s grades are successfully entered!")
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:
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")
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t",
temp["score3"],"\t",temp["total"])
elif key == 5: #Print out the information of all students
print("Next to traverse all student information...")
print("Student ID\tName\tChinese\tMath\tEnglish\tTotal score")
for temp in studentList:
print(temp["ID"],"\t",temp["name"],"\t",temp["score1"],"\t",temp["score2"],"\t",
temp["score3"],"\t",temp["total"])
elif key == 6: # opt out of the system
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")