Python学生成绩管理:计算平均分、最高分及优化技巧

本文将带你使用Python编写程序,处理10个学生6门课程的成绩数据。我们将计算每个学生的平均分、每门课程的平均分,并找出最高分及其所属的学生和课程。

为了使程序更加清晰易懂,我们将使用函数来实现不同的功能。

1. 输入所有学生的每门课成绩pythondef input_scores(): scores = [] for i in range(10): student_scores = [] for j in range(6): score = float(input(f'请输入第{i+1}个学生第{j+1}门课的成绩:')) student_scores.append(score) scores.append(student_scores) return scores

这个函数使用嵌套循环,逐个输入每个学生的每门课成绩,并将所有成绩存储在一个二维列表 scores 中。

2. 计算并输出每个学生的平均分pythondef calculate_student_averages(scores): for i, student_scores in enumerate(scores): average = sum(student_scores) / len(student_scores) print(f'第{i+1}个学生的平均分:{average}')

这个函数遍历 scores 列表,计算每个学生的平均分并输出。

3. 计算并输出每门课程的平均分pythondef calculate_course_averages(scores): for j in range(6): course_scores = [student_scores[j] for student_scores in scores] average = sum(course_scores) / len(course_scores) print(f'第{j+1}门课程的平均分:{average}')

这个函数遍历每一列(代表一门课程),计算该课程的平均分并输出。

4. 输出所有60个分数中最高分及其所对应的学生和课程pythondef find_highest_score(scores): highest_score = scores[0][0] highest_student = 1 highest_course = 1 for i, student_scores in enumerate(scores): for j, score in enumerate(student_scores): if score > highest_score: highest_score = score highest_student = i + 1 highest_course = j + 1 print(f'最高分:{highest_score},来自第{highest_student}个学生,第{highest_course}门课程')

这个函数遍历所有分数,找到最高分,并记录对应的学生和课程信息。

**完整代码:**pythonscores = input_scores()calculate_student_averages(scores)calculate_course_averages(scores)find_highest_score(score


原文地址: http://www.cveoy.top/t/topic/f4lp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录