用python写学生管理系统,列出代码
时间: 2023-12-08 14:02:29 浏览: 100
以下是一个基本的学生管理系统的Python代码示例:
```python
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
class School:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, name):
for student in self.students:
if student.name == name:
self.students.remove(student)
return True
return False
def get_student(self, name):
for student in self.students:
if student.name == name:
return student
return None
def get_all_students(self):
return self.students
def main():
school = School()
while True:
print("1. Add Student")
print("2. Remove Student")
print("3. Get Student")
print("4. Get All Students")
print("5. Quit")
choice = int(input("Enter your choice: "))
if choice == 1:
name = input("Enter student name: ")
age = int(input("Enter student age: "))
grade = int(input("Enter student grade: "))
student = Student(name, age, grade)
school.add_student(student)
elif choice == 2:
name = input("Enter student name: ")
result = school.remove_student(name)
if result:
print("Student removed successfully")
else:
print("Student not found")
elif choice == 3:
name = input("Enter student name: ")
student = school.get_student(name)
if student:
print("Name: ", student.name)
print("Age: ", student.age)
print("Grade: ", student.grade)
else:
print("Student not found")
elif choice == 4:
students = school.get_all_students()
for student in students:
print("Name: ", student.name)
print("Age: ", student.age)
print("Grade: ", student.grade)
elif choice == 5:
break
else:
print("Invalid choice")
if __name__ == '__main__':
main()
```
这个学生管理系统使用了两个类:Student和School。Student类用于创建学生对象,School类用于管理学生。在主函数中,我们使用while循环来显示菜单选项,并根据用户的选择执行不同的操作。用户可以添加、删除、获取单个学生或获取所有学生的详细信息。
阅读全文