python实现简单通讯录管理系统

2023-10-18 1138阅读

ContactBook类包含了添加联系人、删除联系人、搜索联系人和显示联系人等方法。主程序循环显示菜单,根据用户选择执行相应的操作。

下面是一个简单的通讯录管理系统的Python实现:
python
class Contact:
def __init__(self, name, phone):
self.name = name
self.phone = phone
class ContactBook:
def __init__(self):
self.contacts = []
def add_contact(self, name, phone):
contact = Contact(name, phone)
self.contacts.append(contact)
print("Contact added successfully.")
def delete_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
print("Contact deleted successfully.")
return
print("Contact not found.")
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
print("Contact found - Name: {}, Phone: {}".format(contact.name, contact.phone))
return
print("Contact not found.")
def display_contacts(self):
if len(self.contacts) == 0:
print("No contacts found.")
else:
print("Contacts:")
for contact in self.contacts:
print("Name: {}, Phone: {}".format(contact.name, contact.phone))
def menu():
print("1. Add Contact")
print("2. Delete Contact")
print("3. Search Contact")
print("4. Display Contacts")
print("5. Quit")
contact_book = ContactBook()
while True:
menu()
choice = int(input("Enter your choice: "))
if choice == 1:
name = input("Enter name: ")
phone = input("Enter phone number: ")
contact_book.add_contact(name, phone)
elif choice == 2:
name = input("Enter name: ")
contact_book.delete_contact(name)
elif choice == 3:
name = input("Enter name: ")
contact_book.search_contact(name)
elif choice == 4:
contact_book.display_contacts()
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")

该程序使用了两个类:Contact表示一个联系人,ContactBook表示通讯录。ContactBook类包含了添加联系人、删除联系人、搜索联系人和显示联系人等方法。主程序循环显示菜单,根据用户选择执行相应的操作。

python实现简单通讯录管理系统
(图片来源网络,侵删)

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]