python try和except内部函数,用于值错误

时间:2018-09-20 02:17:19

标签: python

nameList = []
scoreList = []
gradeList = []
run = 1
loop = 1

def inputFunction():

className = input("\nWhat is the class name: ")
topic = input("What is the topic: ")
while run == 1:

    studentName = input("What is the students name? Enter 'done' to exit: ")

    if studentName in ("done", "Done"):
        break

    try:
        studentScore = int(input("What is the student's score? "))
    except ValueError:
        print("nonono")

    if studentScore <50:
        grade = "NA"
    if studentScore >49 and studentScore <70:
        grade = "A"
    if studentScore > 69 and studentScore < 90:
        grade = "M"
    if studentScore > 89:
        grade = "E"
    nameList.append(studentName)
    scoreList.append(studentScore)
    gradeList.append(grade)
print("\nClass Name:",className)
print("Class Topic:",topic)

我正在尝试使用try,但变量“ studentScore”除外,但是它给我错误“名称'studentScore'未定义” 任何帮助表示赞赏

2 个答案:

答案 0 :(得分:1)

您可以使用while循环不断询问用户有效的整数,直到用户输入一个整数:

while True:
    try:
        studentScore = int(input("What is the student's score? "))
        break
    except ValueError:
        print("Please enter a valid integer as the student's score.")

答案 1 :(得分:0)

问题是,当try块中的语句引发时,studentScore未定义。

如果引发异常,则应为它提供默认值:

try:
    studentScore = int(input("What is the student's score? "))
except ValueError:
    print("nonono")
    studentScore = 0