用python做一个通讯录
时间: 2024-03-11 12:20:53 浏览: 82
好的,下面是一个简单的通讯录示例代码:
```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, name, phone_number):
contact = Contact(name, phone_number)
self.contacts.append(contact)
def remove_contact(self, name):
for contact in self.contacts:
if contact.name == name:
self.contacts.remove(contact)
def print_contacts(self):
for contact in self.contacts:
print(f"Name: {contact.name}, Phone Number: {contact.phone_number}")
address_book = AddressBook()
while True:
print("1. Add Contact")
print("2. Remove Contact")
print("3. Print Contacts")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
name = input("Enter name: ")
phone_number = input("Enter phone number: ")
address_book.add_contact(name, phone_number)
elif choice == "2":
name = input("Enter name: ")
address_book.remove_contact(name)
elif choice == "3":
address_book.print_contacts()
elif choice == "4":
break
else:
print("Invalid choice")
```
这个通讯录程序有以下功能:
- 添加联系人
- 删除联系人
- 打印联系人列表
- 退出程序
运行程序后,会一直显示菜单供用户选择操作,用户输入对应的数字即可执行相应的操作。
阅读全文