leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python knowledge point series (2)

Estimated reading: 22 minutes 56 views

We have implemented a list of nested dictionaries to hold student information. In this tutorial, we continue to refine the program.

4, Python if else conditional statement

Next, we’re going to ask the user if he wants to add a new student’s information, and if the user enters Yes or Y, we start entering the information. When entering, we need to ensure that the entered number representing the grade meets the requirements, such as greater than or equal to 0 and less than or equal to 100. If the entered grade does not meet the requirements, this element will not be added to the list.

The complete code is as follows.

studentList=[]
student={}
student={"name":"Li Ruoyu","ID":"17","score1":95,"score2":100,"score3":96,"total":291}
studentList.append(student)
student={"name":"Zhang Zidong","ID":"11","score1":93,"score2":100,"score3":95,"total":288}
studentList.append(student)
student={"name":"Wang Xiaoming","ID":"25","score1":100,"score2":94,"score3":100,"total":294}
studentList.append(student)
choice = input("Do you need to enter new student information (Yes/Y means you need to enter)?")
if choice.upper()=="YES" or choice.upper()=="Y":
    isError=False
    student={}
    student["name"]=input("Please enter your name:")
    student["ID"]=input("Please enter the student ID: ")
    score1=float(input("Please enter the language score:"))
    if score1 <= 100 and score1 >= 0 :
        student["score1"]=score1
    else:
        print ("The entered language score is wrong!")
        isError=True
    score2=float(input("Please enter math score:"))
    if score2 <= 100 and score2 >= 0 :
        student["score2"]=score2
    else:
        print ("The entered math grade is wrong!")
        isError=True
    score3=float(input("Please input English score:"))
    if score3 <= 100 and score3 >= 0 :
        student["score3"]=score3
    else:
        print ("The English grade entered is wrong!")
        isError=True
    if isError==False:
        student["total"]=student["score1"] + student["score2"] + student["score3"]
        studentList.append(student)
        print (student["name"]+"'s grades are successfully entered!")
    else:
        print ("Incorrect input, failed to enter grades!")

When the program runs, it asks the user if they need to enter new student information, and assigns the user’s input to the variable choice. Then use the upper method to convert the value of choice to all uppercase, and then determine whether it is equal to YES or Y.

The purpose of using the upper() method here is to ignore the case of user input, that is, whether the user inputs Yes, yes, YES, Y or y, the program considers it to be a valid value. If the input content is not within the range listed above, the program ends. For example, if N is entered, the program ends, as shown in Figure 1.

Python conditional statement
figure 1
If Yes is entered, then the condition is met and the indented clause is executed. First create a variable isError, use it to record whether there is an error in the user input. This variable is initially set to False, when its value becomes True, it means that there is an error in the entry.

Next an empty dictionary student is created. The user is then prompted to enter a name and student ID, and the entered content is used as a value to correspond to the keys “name” and “ID”.

Then prompt the user to enter the language score, if the number entered by the user is not between 0 and 100, the user will be prompted to enter an error, and the isError will be changed to True. If a number between 0 and 100 is entered, the entry will be mapped to the key “score1” as a value.

Then you will be prompted to enter the math score and English score, and will use the same method to interpret whether the entered number is correct. If it is not correct, it will change isError to True.

If isError is equal to True, then it will prompt that the input is wrong, and the input grade fails, as shown in Figure 2.

Python conditional statement
figure 2
If the input is correct, the program will add the result of the Chinese score, math score and English score as the value corresponding to the key “total”. Then use the append() method to add the dictionary student to the studentList list, and prompt that the entry is successful, as shown in Figure 3.

Python conditional statement
image 3
 Using conditions, we can better interact with the user and be able to judge whether the user’s input is correct. However, we are faced with a new problem, that is, each time the program is run, the information can only be entered once, but cannot be entered continuously. It doesn’t matter, below, we will continue to improve this program, introduce how to continuously enter the student’s information and how to find and modify the student’s information.

5. Python while for loop

After learning the loop, we can use the loop to further improve the transcript, so that it can become a really usable program, and solve all the problems raised above, so that it can not only repeatedly enter the student’s information, but also query A student’s grades, you can also modify and delete the student’s information. The complete code is as follows.

studentList=[] 
while True:
    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)
    key = int(input("Please select the function (input serial number 1 to 6): "))
    if key == 1:
        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
   
            score1=float(input("Please enter the language score:"))
            if score1 <= 100 and score1 >= 0 :
                student["score1"]=score1
            else:
                print ("There is an error in the input language score, adding failed!")
                continue
            score2=float(input("Please enter math score:"))
            if score2 <= 100 and score2 >= 0 :
                    student["score2"]=score2
            else:
                print ("The entered math score is incorrect, adding failed!")
                continue
            score3=float(input("Please input English score:"))
            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:
        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:
        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:
                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"))
                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:
                    score1=float(input("Please enter the changed language score:"))
                    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:
                    score2=float(input("Please enter the changed math score:"))
                    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:
                    score3=float(input("Please enter the changed English score:"))
                    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:
        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("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:
         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:
         print("You made a mistake, please try again")

Let’s first analyze what to do.

1. First of all, it is still necessary to define a list to store the student’s information.

2. Then, we let the program run all the time through the while loop, and the program can be closed only when the system is actively requested to exit. The code to be executed later is used as a clause and placed in the while loop.

3. The program displays a list of functions to the user, letting the user know how to make a selection.

4. Then, according to the user’s options, the program uses conditional statements to perform the functions of adding, deleting, modifying, querying, displaying all student information and exiting the program.

5. When adding student information, traverse all the elements in the list through a for loop to determine whether the system already has the same student ID. The addition can be successful only if there is no same student ID.

6. When deleting students, the element to be deleted is also found through the for loop.

7. Modify the student’s information, and also find the specified element through the for loop and modify it.

8. Querying the student’s information also finds the specified element through the for loop.

9. List the information of all students, and print all the elements in the list through the for loop.

Take a look at the code. First, define a list studentList, use it to store the information of all students. Then use a while loop, the condition is True, which means that the loop will continue until a certain condition is met, and then the loop can be jumped out. In this way, the user can continuously enter new student information until he voluntarily exits the program.

studentList=[] 
while True:

All the code that follows are sub-statements of the while loop and need to be indented. Here, a set of function lists will be displayed through the print function to let the user know how to operate, and to be more eye-catching, 30 – signs will be printed on the first line and the last line of the function list as a separation. The user is then prompted to select a function, where they can enter a number between 1 and 6, which is then assigned to the variable key.

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)
     key = int(input("Please select the function (input serial number 1 to 6): "))

Run the program and the result is shown in Figure 4.

python if else loop
Figure 4
Next, the program will complete the corresponding function according to the user’s choice. When the variable key is equal to 1, the program will prompt the user to select the “Add student’s information” function. Then ask the user to enter a name and assign the input to the variable name. Then ask the user to enter the student ID, and the user will be prompted here. The student ID is unique, and repetition is not allowed. Assign the input content to the variable stuId.

Next, the program will verify whether the entered student ID is repeated. First create a temporary variable hasRecord and set it to False. Then use the for loop to traverse each element in the studentList list, and assign each element to the variable temp, which is a dictionary type, so the variable temp is also a dictionary.

Then judge whether the value corresponding to the key “ID” of temp is equal to stuId. If it is equal, it means that there is already the same student ID, the variable hasRecord will be set to True, and the break statement will be called to jump out of the for loop; if it is not equal, do nothing operation, go directly to the next iteration.

After the for loop is executed, judge the variable hasRecord, if its value becomes True, it means there is a duplicate student number, prompting the user to add failure, and then call the continue statement, instead of continuing to execute the following code, but directly return to the while loop at the beginning.

If hasRecord is not equal to True, it means that there are no duplicate student IDs, and the entered student ID is valid, then an empty dictionary student will be created, and the variables name and stuId will be assigned to the student’s keys “name” and “ID” as its corresponding value.

The user is then prompted to enter Chinese, math, and English grades. Determine whether the input number meets the requirements. If it meets the requirements, use the append() method to add the dictionary student to the studentList list, and prompt that the entry is successful; if it does not meet the requirements, it will return to the beginning of the while loop after prompting an input error. The code for judging whether the score is valid has been introduced before and will not be repeated here.

if key == 1:
        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
            score1=float(input("Please enter the language score:"))
            if score1 <= 100 and score1 >= 0 :
                student["score1"]=score1
            else:
                print ("There is an error in the input language score, adding failed!")
                continue
            score2=float(input("Please enter math score:"))
            if score2 <= 100 and score2 >= 0 :
                student["score2"]=score2
            else:
                print ("The entered math score is incorrect, adding failed!")
                continue
            score3=float(input("Please input English score:"))
            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!")

Run the program and the result is shown in Figure 5.

Python if else loop
Figure 5
 When the variable key is equal to 2, the program will prompt the user to select the “delete student’s information” function. Then ask the user to enter the student ID, and assign the input content to the variable stuId.

Next, the program will go to the studentList list to find the element corresponding to the entered student ID. Temporary variables hasRecord and i are created. Use the variable hasRecord to determine whether the corresponding student ID is found. The default value is False. The variable i records the index of the element to be deleted, and the initial value is 0.

Then use a for loop to traverse each element in the studentList list and assign each element to the variable temp. Then judge whether the value corresponding to the key “ID” of temp is equal to stuId. If it is equal, it means that the record is found, the variable hasRecord will be set to True, and the break statement will be called to jump out of the for loop; if it is not equal, the variable i will be incremented by 1, enter the next iteration, and judge the next element.

After the for loop is executed, the variable hasRecord is judged. If the value of hasRecord becomes True, it means that the record to be deleted is found, and the del statement is called to delete the corresponding element in the list. The value of the variable i is the index value of the element to be deleted, and the user is prompted that the deletion is successful. If hasRecord is not equal to True, it means that the corresponding student information is not found, and the user is prompted that the deletion failed.

elif key == 2:
         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!")

Run the program and the result is shown in Figure 6.


Image 6
When the variable key is equal to 3, the program will prompt the user to select the function of “modify student information”. Then ask the user to enter the student ID, and assign the input content to the variable stuId.

Next, the program will go to the studentList list to find the element corresponding to the entered student ID. If hasRecord is equal to False, it means that the corresponding student information is not found, and the user is prompted that the modification fails. Otherwise, it means that the element to be modified is found, and then the while loop is used. The condition is True, which means that the loop will continue until a certain condition is met, and then the loop can be jumped out.

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:")
         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:

Next is the sub-statement of the while loop, which needs to be indented. Prompt the user for input to select the item to be modified, and save the user input to the variable alterNum.

It should be noted that each item that prompts the user to make a choice is followed by a \n, which is an escape character, and its meaning here is to add a newline. If alterNum is equal to 1, it means to modify the name, ask the user to enter the changed name, and assign it to the “name” key of the selected element, prompting the user that the modification is successful, and then call the break statement to jump out of the while loop.

If alterNum is equal to 2, it means to modify the student ID, and the user is required to input the changed student ID. Then confirm that the student number is not repeated through the for loop, assign it to the “ID” key of the selected element, and prompt the user that the modification is successful, and then call the break statement to jump out of the while loop.

If alterNum is equal to 3, it means to modify the language score, requiring the user to input the changed score, and judge the input is a valid value through the conditional statement, and then assign it to the “score1” key of the selected element, and assign “score1”, “score2” and “score3” The sum is assigned to the “total” key, prompting the user that the modification is successful, and then calling the break statement to jump out of the while loop.

If alterNum is equal to 4, it means to modify math scores, which is similar to modifying Chinese scores, and will not be repeated here.

If alterNum is equal to 5, it means to modify English scores, which is similar to modifying Chinese scores, and will not be repeated here.

If alterNum is equal to 6, call the break statement to jump out of the while loop and exit the modification.

If alterNum is equal to any other value, prompt the input to be wrong, and then call the break statement to jump out of the while loop.

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"))
                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:
                    score1=float(input("Please enter the changed language score:"))
                    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:
                    score2=float(input("Please enter the changed math score:"))
                    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:
                    score3=float(input("Please enter the changed English score:"))
                    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")

Run the program and the result is shown in Figure 7.

Python if else loop
Figure 7

Tip: Escape characters refer to replacing some special characters with combinations of ordinary characters. Since these combinations change the meaning of the original characters, they are called “escapes”. Usually, a backslash is added before the specified character \to indicate that the character should be escaped.

Commonly used escape characters in Python are: \n (newline), \r (carriage return), \b (backspace), \’ (single quote), \” (double quote) and \t (horizontal tab) , that is, the Tab key), etc.When the variable key is equal to 4, the program will prompt the user to select the function of “Query Student Information”. Then ask the user to enter the student ID, and assign the entered content to the variable stuId.

Next, the program will go to the studentList list to find the element corresponding to the entered student ID. If hasRecord is equal to False, it means that the corresponding student information is not found, and the user is prompted that the query fails. Otherwise, it means to find the element that needs to be queried, and then print out the information of the element.

When printing student information, we used the escape character again, this time with \t, which means adding a horizontal tab character, which is equivalent to pressing the Tab key. This way, we don’t have to separate each item with spaces as before.

elif key == 4:
         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"])

Run the program and the result is shown in Figure 8.

python if else loop
Figure 8
When the variable key is equal to 5, we will prompt the user to select the “list all students’ information” function. We will iterate over all the elements in the studentList list, and then print out the information for those elements.

elif key == 5:
         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"])

Run the program and the result is shown in Figure 9.

python if else loop
Figure 9
When the variable key is equal to 6, the program will prompt the user whether to confirm to “exit the system”, and ask the user to enter Y or N, and save the user’s input to the quitConfirm variable. If quitConfirm is equal to Y, it means that the user confirms to quit the system, after printing the message “Welcome to use this system, thank you”, call the break statement to jump out of the while loop.

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

Run the program and the result is shown in Figure 10.

python if else loop
Figure 10
 When the variable key is equal to other numbers, the program prompts the user that the input is incorrect and enters the next while loop.

else:
       print("You made a mistake, please try again")

Run the program and the result is shown in Figure 11.

python if else loop

Leave a Comment

CONTENTS