python try and except内部函数的值错误

nameList = []

scoreList = []

gradeList = []

run = 1

loop = 1

定义输入函数():


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)

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


噜噜哒
浏览 195回答 2
2回答

ITMISS

您可以使用while循环不断向用户询问有效整数,直到用户输入一个:while True:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; studentScore = int(input("What is the student's score? "))&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("Please enter a valid integer as the student's score.")

慕桂英3389331

问题是,当 try 块中的语句抛出时,studentScore是未定义的。如果引发异常,您应该给它一个默认值:try:&nbsp; &nbsp; studentScore = int(input("What is the student's score? "))except ValueError:&nbsp; &nbsp; print("nonono")&nbsp; &nbsp; studentScore = 0
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python