Python代码报错‘FinalGrade is not defined’:如何找出最高成绩学生?
解决
FinalGrade is not defined错误并实现加权成绩计算与最高分统计 错误原因分析
finalGrade是aveGrade函数内部的局部变量,函数外部无法直接访问,导致主函数调用max(finalGrade)时触发未定义错误- 未将学生姓名与对应的最终成绩关联存储,无法匹配成绩最高的学生
- 原代码中
max(studentnames)仅会返回姓名字典序最大的学生,并非成绩最高者
修复后的完整代码
def welcome(): print("Hello and Welcome to Top Students") print("Our program lists your students and displays the highest of honors") print("Let's get started\n") def aveGrade(): quizGrade = int(input("What is the grade this student is receiving for their quiz?\n")) # 修正拼写错误:prarticipation → participation partGrade = int(input("What is the grade this student is receiving for their participation?\n")) # 修正语法错误:去掉重复的is assignGrade = int(input("What is the grade this student is receiving for their assignment?\n")) finalGrade = ((quizGrade * .35) + (partGrade * .15) + (assignGrade * .50)) print("The final grade for this student is", finalGrade) # 返回计算好的最终成绩,供主函数存储 return finalGrade def main(): welcome() studentnames = ["Fred", "Daphne", "Velma", "Norville"] # 用字典存储学生姓名与对应最终成绩 student_grades = {} for student in studentnames: print("The current grade standing for", student, "are as follows:\n") # 接收aveGrade返回的成绩并存入字典 student_grades[student] = aveGrade() # 找到成绩最高的学生:通过max函数的key参数指定按成绩排序 top_student = max(student_grades, key=student_grades.get) top_score = student_grades[top_student] print(f"The student with the highest final grade is {top_student} with a total of {top_score}") # 调用主函数执行程序 if __name__ == "__main__": main()
关键修改点
- 返回成绩:修改
aveGrade函数,让其返回计算后的finalGrade,使主函数能获取并存储每个学生的成绩 - 存储关联数据:使用字典
student_grades存储学生姓名与成绩的对应关系,解决成绩与学生匹配的问题 - 修正拼写/语法错误:修复了
prarticipation的拼写错误和输入语句中的重复is - 正确获取最高分:利用
max()函数的key参数,基于字典的值(成绩)找到对应学生,而非仅比较姓名
内容的提问来源于stack exchange,提问作者Creator Combat
相关产品推荐
相关产品推荐

