Python 基于列表实现的通讯录管理系统(包含完整源码)
好的!下面是一个简单的基于列表实现的通讯录管理系统示例。这段代码展示了如何使用 Python 列表进行基本的增、删、查、改操作。
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
def __str__(self):
return f"Name: {self.name}, Phone: {self.phone}, Email: {self.email}"
class AddressBook:
def __init__(self):
self.contacts = []
def add_contact(self, name, phone, email):
new_contact = Contact(name, phone, email)
self.contacts.append(new_contact)
print(f"Contact {name} added successfully.")
def remove_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
print(f"Contact {name} removed successfully.")
return
print(f"Contact {name} not found.")
def update_contact(self, name, phone=None, email=None):
for contact in self.contacts:
if contact.name == name:
if phone:
contact.phone = phone
if email:
contact.email = email
print(f"Contact {name} updated successfully.")
return
print(f"Contact {name} not found.")
def find_contact(self, name):
for contact in self.contacts:
if contact.name == name:
print(contact)
return
print(f"Contact {name} not found.")
def list_contacts(self):
if not self.contacts:
print("Address book is empty.")
for contact in self.contacts:
print(contact)
def main():
address_book = AddressBook()
while True:
print("\nAddress Book Menu:")
print("1. Add Contact")
print("2. Remove Contact")
print("3. Update Contact")
print("4. Find Contact")
print("5. List Contacts")
print("6. Exit")
choice = input("Please enter your choice: ")
if choice == '1':
name = input("Enter name: ")
phone = input("Enter phone: ")
email = input("Enter email: ")
address_book.add_contact(name, phone, email)
elif choice == '2':
name = input("Enter name of the contact to remove: ")
address_book.remove_contact(name)
elif choice == '3':
name = input("Enter name of the contact to update: ")
phone = input("Enter new phone (or press enter to skip): ")
email = input("Enter new email (or press enter to skip): ")
address_book.update_contact(name, phone if phone else None, email if email else None)
elif choice == '4':
name = input("Enter name of the contact to find: ")
address_book.find_contact(name)
elif choice == '5':
address_book.list_contacts()
elif choice == '6':
print("Exiting the Address Book.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
功能说明
- 添加联系人:输入姓名、电话和电子邮件,将联系人添加到通讯录。
- 删除联系人:根据姓名删除指定联系人。
- 更新联系人:更新联系人信息(电话和/或电子邮件)。
- 查找联系人:按姓名查找并显示联系人信息。
- 列出所有联系人:显示所有联系人信息。
- 退出:退出程序。
这个简单的通讯录管理系统使用列表来存储联系人信息,通过菜单选项执行各种操作。你可以根据需要进一步扩展和优化这段代码。