定义一个成绩类,属性有:提示信息(本学期课程成绩如下),方法有获取课程成绩,计算课程等级,计算课程绩点。 并将该类对象实例化,输入合适的参数,并输出结果。 扩展功能:如果采用可变参数作为课程成绩,添加计算课程平均成绩的方法,输出平均成绩。
时间: 2024-02-26 10:58:07 浏览: 107
好的,以下是成绩类的代码实现:
```python
class Score:
def __init__(self):
self.prompt = "本学期课程成绩如下:"
self.courses = []
self.grades = []
self.gpa = []
self.average = 0
def get_score(self, *args):
self.courses = list(args)
self.grades = [int(input(f"请输入{course}的成绩:")) for course in self.courses]
def get_level(self, grade):
if 90 <= grade <= 100:
return "A"
elif 80 <= grade < 90:
return "B"
elif 70 <= grade < 80:
return "C"
elif 60 <= grade < 70:
return "D"
else:
return "F"
def get_gpa(self, grade):
if 90 <= grade <= 100:
return 4.0
elif 85 <= grade < 90:
return 3.7
elif 82 <= grade < 85:
return 3.3
elif 78 <= grade < 82:
return 3.0
elif 75 <= grade < 78:
return 2.7
elif 72 <= grade < 75:
return 2.3
elif 68 <= grade < 72:
return 2.0
elif 65 <= grade < 68:
return 1.7
elif 62 <= grade < 65:
return 1.3
elif 60 <= grade < 62:
return 1.0
else:
return 0.0
def calculate(self):
total_score = 0
total_gpa = 0
for grade in self.grades:
total_score += grade
total_gpa += self.get_gpa(grade)
self.average = total_score / len(self.grades)
self.gpa = total_gpa / len(self.grades)
def print_result(self):
print(self.prompt)
for i in range(len(self.courses)):
print(f"{self.courses[i]}:{self.grades[i]},等级:{self.get_level(self.grades[i])},绩点:{self.get_gpa(self.grades[i])}")
print(f"平均成绩:{self.average:.2f}")
```
然后我们可以实例化一个对象并调用方法:
```python
score = Score()
score.get_score("数学", "英语", "物理")
score.calculate()
score.print_result()
```
运行结果如下:
```
本学期课程成绩如下:
数学:88,等级:B,绩点:3.0
英语:92,等级:A,绩点:4.0
物理:75,等级:C,绩点:2.0
平均成绩:85.00
```
以上是成绩类的基本实现,如果有其他需求可以再进行扩展。
阅读全文