python實(shí)現(xiàn)簡(jiǎn)單通訊錄管理系統(tǒng)

小云
144
2023-08-17 14:08:53

下面是一個(gè)簡(jiǎn)單的通訊錄管理系統(tǒng)的Python實(shí)現(xiàn):

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.")

該程序使用了兩個(gè)類(lèi):Contact表示一個(gè)聯(lián)系人,ContactBook表示通訊錄。ContactBook類(lèi)包含了添加聯(lián)系人、刪除聯(lián)系人、搜索聯(lián)系人和顯示聯(lián)系人等方法。主程序循環(huán)顯示菜單,根據(jù)用戶選擇執(zhí)行相應(yīng)的操作。

0