为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

噜噜哒 2021-06-21 13:19:38
nameList = []scoreList = []gradeList = []run = 1loop = 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'未定义”任何帮助表示赞赏
查看完整描述

2 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

您可以使用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.")


查看完整回答
反对 回复 2021-06-22
?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

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


如果引发异常,您应该给它一个默认值:


try:

    studentScore = int(input("What is the student's score? "))

except ValueError:

    print("nonono")

    studentScore = 0


查看完整回答
反对 回复 2021-06-22
  • 2 回答
  • 0 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信