利用python实现一个学生管理系统(完整代码)

点赞加关注,学习不迷路!

下面是一个学生管理系统示例,使用Python语言和文件来保存和读取学生信息:

import os

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

class StudentManagementSystem:
    def __init__(self):
        self.students = []

    def add_student(self, name, age, grade):
        student = Student(name, age, grade)
        self.students.append(student)
        self.save_students()

    def remove_student(self, name):
        self.students = [student for student in self.students if student.name != name]
        self.save_students()

    def show_students(self):
        for student in self.students:
            print(f"Name: {student.name}, Age: {student.age}, Grade: {student.grade}")

    def save_students(self):
        with open("students.txt", "w") as file:
            for student in self.students:
                file.write(f"{student.name},{student.age},{student.grade}\n")

    def load_students(self):
        if os.path.exists("students.txt"):
            with open("students.txt", "r") as file:
                lines = file.readlines()
                for line in lines:
                    name, age, grade = line.strip().split(",")
                    student = Student(name, int(age), int(grade))
                    self.students.append(student)

if __name__ == "__main__":
    system = StudentManagementSystem()
    system.load_students()

    while True:
        print("\n1. Add student")
        print("2. Remove student")
        print("3. Show students")
        print("4. Exit")

        choice = int(input("Enter your choice: "))

        if choice == 1:
            name = input("Enter name: ")
            age = int(input("Enter age: "))
            grade = int(input("Enter grade: "))
            system.add_student(name, age, grade)
        elif choice == 2:
            name = input("Enter name: ")
            system.remove_student(name)
        elif choice == 3:
            system.show_students()
        elif choice == 4:
            break
        else:
            print("Invalid choice, please try again!")

注:

Student类用于表示一个学生,包含nameagegrade三个属性。StudentManagementSystem类用于管理学生信息,包含添加学生、删除学生和显示学生信息等功能,还有一个load_students()方法和一个save_students()方法用于读取和保存学生信息到文件中。在main函数中,使用一个无限循环不断显示菜单,根据用户选择执行相应的操作,最后通过输入4退出系统。在该示例中,学生信息被保存在一个名为students.txt的文件中。

你可能感兴趣的:(python)