Python为什么我在这里得到一个ValueError?

2024-05-03 12:10:37 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我想一直提示用户输入choice,直到他们输入的不是1-5,而是一些选项(例如2),程序在ValueError之后直接进入“再见”:

   if(genRoster(fileName, recordsDict) and fileName != ""):
        hwPts = 250
        print("Select an option: ")
        try:
            choice = int(input("1) Get lab scores \n2) Get homework scores \n3) Get midterm exam scores \n4) Get final exam scores \n5) Get overall grades\n").strip())
            while(choice > 0 and choice < 6):
                print("Name      %")
                if(choice == 1):
                    for name in recordsDict.keys():
                        print(name+"      "+str(student.getLPGrade(recordsDict[name]))+"%") # 6 spaces
                    print("Class     "+str(getLpAvg(recordsDict))+"%\n")
                elif(choice == 2):
                    for name in recordsDict.keys():
                        print(name+"      "+str(student.getHWGrade(recordsDict[name], hwPts))+"%") # 6 spaces
                    print('Class     % 1.1f' %getHwAvg(recordsDict, hwPts), "%\n")

                elif (choice == 3):
                    for name in recordsDict.keys():
                        print(name + "      " + str(student.getMTGrade(recordsDict[name])) + "%")  # 6 spaces
                    print("Class     " + str(getMtAvg(recordsDict)) + "%\n")
                elif (choice == 4):
                    for name in recordsDict.keys():
                        print(name + "      " + str(student.getFEGrade(recordsDict[name])) + "%")  # 6 spaces
                    print("Class     " + str(getFeAvg(recordsDict)) + "%\n")
                elif (choice == 5):
                    for name in recordsDict.keys():
                        print(name + "      " + str(student.getOverallGrade(recordsDict[name], hwPts)) + "%")  # 6 spaces
                    print("Class     ", str(getOvAvg(recordsDict, hwPts)), "%\n")
                print("Select an option: ")
                choice = int(input("1) Get lab scores \n2) Get homework scores \n3) Get midterm exam scores \n4) Get final exam scores \n5) Get overall grades\n"))
        except ValueError:
            print("Goodbye! 2")
    else:
        print("Goodbye!")

recordsDict是一个字典,其中包含由

def genStud(studentName, labScores, hwScores, midtermScore, finalScore):
    return studentName, {"NAME": str(studentName).strip().title(), "LP": labScores, "HW": hwScores, "MT": int(midtermScore), "FE": int(finalScore)}

但这不应影响选择。这里发生了什么


Tags: nameinforgetkeysstudentclassint