import math
class Student(object):
def __init__(self, id, name, chinese, math, english):
self.id = id
self.name = name
self.chinese = chinese
self.math = math
self.english = english
self.ave_score = (chinese+math+english)/3.0
def verifyInput(item, type):
'''验证成绩是否是在合法的输入范围内
如果不合法就继续输入
Args:
item(int):学生编号
type(str):课程类型
Returns:
score:对应科目的成绩
'''
score = float(input('请输入第{}个学生的{}成绩:'.format(item, type)))
while score < 0 or score > 100:
score = float(input('输入有误,请重新输入第{}个学生的{}成绩:'.format(item, type)))
return score
if __name__ == '__main__':
# 定义学生列表
students = list()
# 输入学生成绩
for item in range(1, 6):
id = int(input('请输入第{}个学生的学号:'.format(item)))
name = str(input('请输入第{}个学生的姓名:'.format(item)))
chinese = verifyInput(item,'语文')
math = verifyInput(item, '数学')
english = verifyInput(item, '英语')
students.append(Student(id, name, chinese, math, english))
# 排序
students.sort(key=lambda x: x.ave_score, reverse=True)
# 新建list记录各科总和
score = [0, 0, 0]
print("学号\t姓名\t语文\t数学\t英语\t学生平均成绩")
for student in students:
score[0] += student.chinese
score[1] += student.math
score[2] += student.english
print(
"{:2}\t{:3}\t{:3}\t{:3}\t{:3}\t{:3} ".format(
student.id, student.name, student.chinese, student.math, student.english, student.ave_score))
# 计算各科平均成绩
score = [i/5 for i in score]
print("课程平均分\t{:3}\t{:3}\t{:3}".format(*score))