Python 编写程序实现在某次考试后录入某班学生的成绩,不同班级学生人数不固定,最后统计该班级的平均分、最高分和最低分
时间: 2024-02-13 12:07:31 浏览: 39
好的,我可以为您提供这样一个 Python 程序的框架,您可以根据自己的需求进行修改:
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
class Class:
def __init__(self):
self.students = []
def add_student(self, name, score):
student = Student(name, score)
self.students.append(student)
def get_average_score(self):
sum_score = 0
for student in self.students:
sum_score += student.score
return sum_score / len(self.students)
def get_max_score(self):
max_score = 0
for student in self.students:
if student.score > max_score:
max_score = student.score
return max_score
def get_min_score(self):
min_score = float('inf')
for student in self.students:
if student.score < min_score:
min_score = student.score
return min_score
# 示例用法
c = Class()
c.add_student('张三', 80)
c.add_student('李四', 90)
c.add_student('王五', 70)
print(c.get_average_score()) # 80.0
print(c.get_max_score()) # 90
print(c.get_min_score()) # 70
```
这个程序包括两个类:`Student` 和 `Class`。`Student` 类表示一个学生,包含学生的姓名和成绩两个属性;`Class` 类表示一个班级,包含学生列表和计算平均分、最高分、最低分三个方法。
在 `Class` 类中,`add_student` 方法用于添加一个学生;`get_average_score` 方法用于计算平均分;`get_max_score` 和 `get_min_score` 方法分别用于计算最高分和最低分。
在示例用法中,首先创建了一个 `Class` 对象,然后添加了三个学生,最后分别调用了计算平均分、最高分、最低分的方法,并将结果输出到屏幕上。