有一个班4个学生,5门课。 (1).求第一门课的平均分; (2).找出有两门以上课程不及格的学生, 输出他们的姓名、全部课程成绩及平均成绩; (3).找出平均成绩在90分以上或全部课程成绩在 85分以上的学生。分别编3个函数实现以上3个要求。
时间: 2024-12-24 18:17:13 浏览: 14
为了满足上述需求,我们可以创建一个简单的Python类`Student`来表示每个学生,以及一个包含所有学生信息的`Class`类。以下是三个函数的实现:
```python
class Student:
def __init__(self, name):
self.name = name
self.grades = {i: None for i in range(1, 6)}
def set_grade(self, course, grade):
if 1 <= course <= 5:
self.grades[course] = grade
def get_average_grade(self):
total = sum(self.grades.values())
return total / len(self.grades) if total != 0 else 0
class Class:
def __init__(self):
self.students = []
def add_student(self, name):
student = Student(name)
self.students.append(student)
def average_grade_of_course_1(self):
total_grades = [student.grades[1] for student in self.students if student.grades[1]]
return sum(total_grades) / len(total_grades) if total_grades else "No grades available"
def students_with_two_or_more_fails(self):
result = []
for student in self.students:
fails = [grade for grade in student.grades.values() if grade < 60]
if len(fails) >= 2:
avg_grade = student.get_average_grade()
result.append((student.name, student.grades, avg_grade))
return result
def high_average_students(self):
high_scores = [student for student in self.students if student.get_average_grade() >= 90 or all(grade >= 85 for grade in student.grades.values())]
return [student.name for student in high_scores]
# 使用示例
class_instance = Class()
class_instance.add_student("Alice")
class_instance.add_student("Bob")
class_instance.add_student("Charlie")
class_instance.add_student("Dave")
# ... 分别设置学生的成绩 ...
average_course1 = class_instance.average_grade_of_course_1()
students_with_fails = class_instance.students_with_two_or_more_fails()
high_score_students = class_instance.high_average_students()
print(f"First Course Average: {average_course1}")
print("Students with two or more failures:")
for student_info in students_with_fails:
print(student_info)
print("High score students:", high_score_students)
```
这个代码首先定义了`Student`和`Class`类,然后创建了一个班级实例并添加了学生。之后,通过调用相应的函数获取所需的统计信息。
阅读全文