Python学生信息管理系统代码讲解
时间: 2023-11-05 14:31:23 浏览: 83
好的,我可以为您讲解一下Python学生信息管理系统的代码。
首先,我们需要定义一个学生类,包含学生的姓名、学号、性别和成绩等信息。代码如下:
```python
class Student:
def __init__(self, name, id, gender, score):
self.name = name
self.id = id
self.gender = gender
self.score = score
```
接着,我们需要定义一个管理系统类,包含添加学生、删除学生、修改学生信息、查询学生信息等功能。代码如下:
```python
class StudentManagementSystem:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
def remove_student(self, id):
for student in self.students:
if student.id == id:
self.students.remove(student)
def modify_student(self, id, name, gender, score):
for student in self.students:
if student.id == id:
student.name = name
student.gender = gender
student.score = score
def query_student(self, id):
for student in self.students:
if student.id == id:
return student
def query_all_students(self):
return self.students
```
在主函数中,我们可以通过用户输入来实现对学生信息的操作,如添加学生、删除学生、修改学生信息、查询学生信息等。代码如下:
```python
def main():
sms = StudentManagementSystem()
while True:
print("1. Add student")
print("2. Remove student")
print("3. Modify student information")
print("4. Query student information")
print("5. Query all students")
print("0. Exit")
choice = int(input("Please enter your choice: "))
if choice == 1:
name = input("Please enter student name: ")
id = input("Please enter student id: ")
gender = input("Please enter student gender: ")
score = input("Please enter student score: ")
student = Student(name, id, gender, score)
sms.add_student(student)
elif choice == 2:
id = input("Please enter student id: ")
sms.remove_student(id)
elif choice == 3:
id = input("Please enter student id: ")
name = input("Please enter student name: ")
gender = input("Please enter student gender: ")
score = input("Please enter student score: ")
sms.modify_student(id, name, gender, score)
elif choice == 4:
id = input("Please enter student id: ")
student = sms.query_student(id)
if student:
print("{}, {}, {}, {}".format(student.name, student.id, student.gender, student.score))
else:
print("No such student")
elif choice == 5:
students = sms.query_all_students()
for student in students:
print("{}, {}, {}, {}".format(student.name, student.id, student.gender, student.score))
elif choice == 0:
break
else:
print("Invalid choice, please try again")
if __name__ == "__main__":
main()
```
以上就是Python学生信息管理系统的代码讲解,通过这个简单的例子,我们可以学习到Python面向对象编程的基础知识。
阅读全文