阅读量:0
下面是一个简单的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
函数中,通过一个无限循环,根据用户的选择执行相应的操作,包括添加联系人、删除联系人、搜索联系人、显示所有联系人以及退出程序。
注意:上述代码只是一个简单的示例,实际的通讯录程序可能需要更多的功能和优化。