4、使用Python语言开发一个简单的学生管理系统。运用该学生管理系统编辑学生的信息,适时更新学生的资料。例如,新生入校,要在学生管理系统中录入刚入校的学生信息。请实现一个学生管理系统,要求如下。 (1)使用
时间: 2024-04-30 17:20:05 浏览: 44
Python语言开发。 (2)实现添加学生信息、查询学生信息、修改学生信息、删除学生信息等基本功能。 (3)学生信息至少包括学号、姓名、年龄、性别、班级等基本信息。 (4)学生信息应当能够以文件的形式进行保存和读取。
这里提供一个基本的学生管理系统的代码示例:
```python
import os
class Student:
def __init__(self, id, name, age, gender, class_name):
self.id = id
self.name = name
self.age = age
self.gender = gender
self.class_name = class_name
def __str__(self):
return f"{self.id} {self.name} {self.age} {self.gender} {self.class_name}"
class StudentManager:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, student_id):
for student in self.students:
if student.id == student_id:
self.students.remove(student)
return True
return False
def get_student(self, student_id):
for student in self.students:
if student.id == student_id:
return student
return None
def get_all_students(self):
return self.students
def save_to_file(self, file_path):
with open(file_path, "w") as f:
for student in self.students:
f.write(str(student) + "\n")
def read_from_file(self, file_path):
if not os.path.exists(file_path):
return
with open(file_path, "r") as f:
lines = f.readlines()
for line in lines:
parts = line.strip().split()
student = Student(parts[0], parts[1], parts[2], parts[3], parts[4])
self.add_student(student)
if __name__ == "__main__":
manager = StudentManager()
manager.read_from_file("students.txt")
while True:
print("1. 添加学生")
print("2. 查询学生")
print("3. 修改学生")
print("4. 删除学生")
print("5. 显示所有学生")
print("6. 退出")
choice = input("请选择操作:")
if choice == "1":
id = input("请输入学号:")
name = input("请输入姓名:")
age = input("请输入年龄:")
gender = input("请输入性别:")
class_name = input("请输入班级:")
student = Student(id, name, age, gender, class_name)
manager.add_student(student)
manager.save_to_file("students.txt")
elif choice == "2":
id = input("请输入学号:")
student = manager.get_student(id)
if student is not None:
print(student)
else:
print("学生不存在")
elif choice == "3":
id = input("请输入学号:")
student = manager.get_student(id)
if student is not None:
name = input("请输入姓名:")
age = input("请输入年龄:")
gender = input("请输入性别:")
class_name = input("请输入班级:")
student.name = name
student.age = age
student.gender = gender
student.class_name = class_name
manager.save_to_file("students.txt")
else:
print("学生不存在")
elif choice == "4":
id = input("请输入学号:")
if manager.remove_student(id):
manager.save_to_file("students.txt")
print("删除成功")
else:
print("学生不存在")
elif choice == "5":
students = manager.get_all_students()
for student in students:
print(student)
elif choice == "6":
break
else:
print("无效的操作")
```
其中,`Student`类表示一个学生,包含学号、姓名、年龄、性别、班级等属性。`StudentManager`类表示学生管理器,包含添加、删除、查询、修改等基本操作。学生信息可以以文件的形式进行保存和读取。在主函数中,使用循环来实现菜单式的操作界面,根据用户输入的选择执行相应的操作。
阅读全文