写一个python成绩计算的代码
时间: 2024-09-18 20:13:36 浏览: 67
当然可以,这是一个简单的Python代码示例,用于计算学生成绩并支持加权平均:
```python
class Student:
def __init__(self, name):
self.name = name
self.grades = {}
def add_grade(self, subject, grade, weight=1):
"""
添加单门课程的成绩及权重
"""
if subject not in self.grades:
self.grades[subject] = {'grade': grade, 'weight': weight}
else:
raise ValueError(f"Subject {subject} already exists with a different weight.")
def calculate_average(self):
"""
计算总成绩和加权平均分
"""
total_score = sum(grade['grade'] * grade['weight'] for grade in self.grades.values())
weighted_avg = total_score / sum(weight for grade in self.grades.values())
return weighted_avg
def display_report(self):
print(f"Student: {self.name}")
total_grades = "\n".join(f"{subject}: Grade - {grades['grade']} (Weight: {grades['weight']})" for subject, grades in self.grades.items())
print("Grade Report:\n", total_grades)
print(f"Average Score: {self.calculate_average()}")
# 示例
student1 = Student("张三")
student1.add_grade('数学', 90, 2)
student1.add_grade('语文', 85, 1)
student1.add_grade('英语', 95, 1.5) # 示例中加权分数
student1.display_report()
```
在这个例子中,我们创建了一个`Student`类,它有姓名、成绩字典和一些方法。用户可以添加成绩和查看报告,以及计算加权平均分。
阅读全文