功能描述:
- 添加学生:输入学生ID、姓名、年龄,初始化成绩为0。
- 删除学生:根据学生ID删除学生信息。
- 更新学生:可以更新学生的姓名、年龄及成绩。
- 查看学生:查看所有学生的信息,包括基本信息和成绩。
- 按总分排序:根据学生的总分进行排序,并显示排序后的学生信息。实现录入三门课语、数、英的成绩信息,总分及平均分,并根据名次排名。
- 退出:退出系统并保存数据到
students.json
文件中。
系统在启动时会从students.json
文件中读取学生数据,在添加、删除或更新学生信息后会自动保存数据。
完整代码:
import json
class Student:
def __init__(self, student_id, name, age):
self.student_id = student_id
self.name = name
self.age = age
self.grades = {"语文": 0, "数学": 0, "英语": 0}
self.total = 0
self.average = 0
def update_grades(self, grades):
self.grades.update(grades)
self.calculate_total_and_average()
def calculate_total_and_average(self):
self.total = sum(self.grades.values())
self.average = self.total / len(self.grades)
def to_dict(self):
return {
"student_id": self.student_id,
"name": self.name,
"age": self.age,
"grades": self.grades,
"total": self.total,
"average": self.average
}
@classmethod
def from_dict(cls, data):
student = cls(data['student_id'], data['name'], data['age'])
student.grades = data['grades']
student.total = data['total']
student.average = data['average']
return student
class StudentManagementSystem:
def __init__(self, filename='students.json'):
self.filename = filename
self.students = self.load_students()
def add_student(self, student):
self.students.append(student)
self.save_students()
def delete_student(self, student_id):
self.students = [s for s in self.students if s.student_id != student_id]
self.save_students()
def update_student(self, student_id, name=None, age=None, grades=None):
for student in self.students:
if student.student_id == student_id:
if name:
student.name = name
if age:
student.age = age
if grades:
student.update_grades(grades)
self.save_students()
def view_students(self):
return self.students
def sort_students_by_total(self):
self.students.sort(key=lambda x: x.total, reverse=True)
def save_students(self):
with open(self.filename, 'w') as f:
json.dump([s.to_dict() for s in self.students], f, indent=4)
def load_students(self):
try:
with open(self.filename, 'r') as f:
return [Student.from_dict(data) for data in json.load(f)]
except FileNotFoundError:
return []
def main():
sms = StudentManagementSystem()
print('--------------------------------')
print(' 欢迎来到学生信息管理系统 ')
print('-------------------------------')
while True:
print("\n1. 添加学生")
print("2. 删除学生")
print("3. 更新学生")
print("4. 查看学生")
print("5. 按总分排序学生")
print("6. 退出")
choice = input("请输入你的选择: ")
if choice == '1':
student_id = int(input("请输入学生ID: "))
name = input("请输入学生姓名: ")
age = int(input("请输入学生年龄: "))
sms.add_student(Student(student_id, name, age))
elif choice == '2':
student_id = int(input("请输入要删除的学生ID: "))
sms.delete_student(student_id)
elif choice == '3':
student_id = int(input("请输入要更新的学生ID: "))
name = input("请输入新的学生姓名 (留空则不更新): ")
age = input("请输入新的学生年龄 (留空则不更新): ")
age = int(age) if age else None
grades = {}
while True:
subject = input("请输入要更新的学科名 (语文/数学/英语, 输入 'done' 完成): ")
if subject.lower() == 'done':
break
grade = input(f"请输入 {subject} 的新成绩 (留空则不更新): ")
if grade:
grades[subject] = float(grade)
sms.update_student(student_id, name if name else None, age, grades)
elif choice == '4':
students = sms.view_students()
for student in students:
grades_str = ", ".join([f"{subject}: {grade}" for subject, grade in student.grades.items()])
print(f"ID: {student.student_id}, Name: {student.name}, Age: {student.age}, Grades: {grades_str}, Total: {student.total}, Average: {student.average:.2f}")
elif choice == '5':
sms.sort_students_by_total()
print("学生已按总分排序。")
students = sms.view_students()
for student in students:
grades_str = ", ".join([f"{subject}: {grade}" for subject, grade in student.grades.items()])
print(f"ID: {student.student_id}, Name: {student.name}, Age: {student.age}, Grades: {grades_str}, Total: {student.total}, Average: {student.average:.2f}")
elif choice == '6':
break
else:
print("无效的选择,请重新输入。")
if __name__ == "__main__":
main()