考试评分程序函数传参异常:返回变量未被引用问题求助
考试评分程序变量未定义问题修复
问题根源
- 调用
userinput()时未接收返回值,导致allinputs变量未定义 - 调用
points()、pass_percentage()等函数时未接收返回结果,后续使用的gradepoints、passorfail等变量均未在主程序中声明 - 两处逻辑小问题:
pass_percentage中通过率计算错误(用通过人数除以不及格人数,而非总人数)grades_distribution中打印等级的循环缺少计数器递减,会触发无限循环
修正后的完整代码
def userinput(): allinputs = [] while True: try: results = list(map(int, input('Exam points and exercises completed: ').split(' '))) allinputs.append(results) except ValueError: break return allinputs def points(allinputs): exampoints = [] exercises = [] exercises_converted = [] gradepoints = [] counter = 0 for i in allinputs: exampoints.append(i[0]) exercises.append(i[1]) for e in exercises: exercises_converted.append(e//10) for p in exampoints: p2 = exercises_converted[counter] gradepoints.append(p + p2) counter += 1 return (gradepoints, exampoints, exercises_converted) def average(gradepoints): avg_float = sum(gradepoints) / len(gradepoints) points_avg = round(avg_float, 1) return points_avg def pass_percentage(exercises_converted, exampoints): failexam = [] passexam = [] passorfail = [] i = 0 while i < len(exampoints): if exampoints[i] < 10 or exercises_converted[i] + exampoints[i] < 15: failexam.append("fail") passorfail.append(0) else: passexam.append("pass") passorfail.append(1) i += 1 # 修正通过率计算:通过人数/总人数,处理空列表情况 total = len(exampoints) percentage_float = len(passexam)/total if total > 0 else 0 percentage = round(percentage_float * 100, 1) # 转为百分比格式 return (percentage, passorfail) def grades_distribution(passorfail, gradepoints): grades = [] i = 0 l = 5 while i < len(gradepoints): if passorfail[i] == 0: grades.append(0) elif passorfail[i] != 0 and gradepoints[i] >= 15 and gradepoints[i] <= 17: grades.append(1) elif passorfail[i] != 0 and gradepoints[i] >= 18 and gradepoints[i] <= 20: grades.append(2) elif passorfail[i] != 0 and gradepoints[i] >= 21 and gradepoints[i] <= 23: grades.append(3) elif passorfail[i] != 0 and gradepoints[i] >= 24 and gradepoints[i] <= 27: grades.append(4) elif passorfail[i] != 0 and gradepoints[i] >= 28 and gradepoints[i] <= 30: grades.append(5) i += 1 # 添加l -= 1避免无限循环 while l >= 0: print(l, ": ", "*" * grades.count(l)) l -= 1 return # 主程序修正:接收所有函数返回值 allinputs = userinput() print("Statistics:") gradepoints, exampoints, exercises_converted = points(allinputs) print(f"Points average: {average(gradepoints)}") percentage, passorfail = pass_percentage(exercises_converted, exampoints) print(f"Pass percentage: {percentage}%") print("Grade distribution") grades_distribution(passorfail, gradepoints)
关键修改点
- 将
userinput()的返回值赋值给allinputs变量,确保后续调用points()时有合法参数 - 接收
points()返回的三个变量,供后续函数使用 - 接收
pass_percentage()返回的通过率和及格状态列表 - 修正通过率计算逻辑,改为通过人数除以总人数,并转为百分比格式
- 在
grades_distribution的打印循环中添加l -= 1,终止循环
内容的提问来源于stack exchange,提问作者Josiah Peace
相关产品推荐
相关产品推荐

