用python代码写学生通讯录管理系统,有添加,删除,查找,修改,展示,文件保存等功能的代码
时间: 2024-02-28 18:56:54 浏览: 60
好的,下面是一个简单的学生通讯录管理系统的 Python 代码,实现了添加、删除、查找、修改、展示和文件保存功能:
```python
import pickle
class Student:
def __init__(self, name, age, gender, phone):
self.name = name
self.age = age
self.gender = gender
self.phone = phone
class StudentBook:
def __init__(self):
self.students = []
def add_student(self, student):
self.students.append(student)
print('添加成功!')
def remove_student(self, name):
for student in self.students:
if student.name == name:
self.students.remove(student)
print('删除成功!')
return
print('未找到该学生!')
def find_student(self, name):
for student in self.students:
if student.name == name:
print('姓名:', student.name)
print('年龄:', student.age)
print('性别:', student.gender)
print('电话:', student.phone)
return
print('未找到该学生!')
def modify_student(self, name, age, gender, phone):
for student in self.students:
if student.name == name:
student.age = age
student.gender = gender
student.phone = phone
print('修改成功!')
return
print('未找到该学生!')
def show_students(self):
for student in self.students:
print('姓名:', student.name)
print('年龄:', student.age)
print('性别:', student.gender)
print('电话:', student.phone)
print('------------------------')
def save_to_file(self, file_name):
with open(file_name, 'wb') as f:
pickle.dump(self.students, f)
print('保存成功!')
def load_from_file(self, file_name):
with open(file_name, 'rb') as f:
self.students = pickle.load(f)
print('加载成功!')
def main():
student_book = StudentBook()
while True:
print('请选择操作:')
print('1. 添加学生')
print('2. 删除学生')
print('3. 查找学生')
print('4. 修改学生')
print('5. 展示所有学生')
print('6. 保存到文件')
print('7. 从文件加载')
print('0. 退出')
choice = input()
if choice == '1':
name = input('请输入姓名:')
age = input('请输入年龄:')
gender = input('请输入性别:')
phone = input('请输入电话:')
student = Student(name, age, gender, phone)
student_book.add_student(student)
elif choice == '2':
name = input('请输入姓名:')
student_book.remove_student(name)
elif choice == '3':
name = input('请输入姓名:')
student_book.find_student(name)
elif choice == '4':
name = input('请输入姓名:')
age = input('请输入年龄:')
gender = input('请输入性别:')
phone = input('请输入电话:')
student_book.modify_student(name, age, gender, phone)
elif choice == '5':
student_book.show_students()
elif choice == '6':
file_name = input('请输入文件名:')
student_book.save_to_file(file_name)
elif choice == '7':
file_name = input('请输入文件名:')
student_book.load_from_file(file_name)
elif choice == '0':
break
else:
print('输入错误,请重新输入!')
if __name__ == '__main__':
main()
```
这个代码中,我们定义了两个类,`Student` 类表示一个学生,包含姓名、年龄、性别、电话等属性,`StudentBook` 类表示学生通讯录,包含添加、删除、查找、修改、展示和文件保存等功能。在 `main` 函数中,我们使用一个 `while` 循环来不断接受用户输入,并根据用户的选择来调用不同的函数实现不同的功能。通过这个代码,你可以学习到如何使用 Python 的类、列表、字典、文件读写等基本语法和数据结构来实现一个简单的学生通讯录管理系统。
阅读全文