下面是一個簡單的Python通訊錄程序代碼示例:
class Contact:
def __init__(self, name, phone_number):
self.name = name
self.phone_number = phone_number
class AddressBook:
def __init__(self):
self.contacts = []
def add_contact(self, contact):
self.contacts.append(contact)
def remove_contact(self, contact):
self.contacts.remove(contact)
def search_contact(self, name):
for contact in self.contacts:
if contact.name == name:
return contact
return None
def display_contacts(self):
if len(self.contacts) == 0:
print("No contacts found.")
else:
for contact in self.contacts:
print(f"Name: {contact.name}, Phone Number: {contact.phone_number}")
def main():
address_book = AddressBook()
while True:
print("1. Add Contact")
print("2. Remove Contact")
print("3. Search Contact")
print("4. Display All Contacts")
print("5. Quit")
choice = input("Enter your choice: ")
if choice == "1":
name = input("Enter name: ")
phone_number = input("Enter phone number: ")
contact = Contact(name, phone_number)
address_book.add_contact(contact)
print("Contact added.")
elif choice == "2":
name = input("Enter name: ")
contact = address_book.search_contact(name)
if contact:
address_book.remove_contact(contact)
print("Contact removed.")
else:
print("Contact not found.")
elif choice == "3":
name = input("Enter name: ")
contact = address_book.search_contact(name)
if contact:
print(f"Name: {contact.name}, Phone Number: {contact.phone_number}")
else:
print("Contact not found.")
elif choice == "4":
address_book.display_contacts()
elif choice == "5":
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
這個程序通過創建Contact
類和AddressBook
類來實現通訊錄的功能。Contact
類用于表示一個聯系人,包含姓名和電話號碼兩個屬性。AddressBook
類用于表示通訊錄,包含一個聯系人列表,以及添加、刪除、搜索和顯示聯系人的方法。
在main
函數中,通過一個無限循環,根據用戶的選擇執行相應的操作,包括添加聯系人、刪除聯系人、搜索聯系人、顯示所有聯系人以及退出程序。
注意:上述代碼只是一個簡單的示例,實際的通訊錄程序可能需要更多的功能和優化。