用python写通讯录
时间: 2024-10-10 21:05:03 浏览: 43
在Python中创建一个简单的通讯录程序,我们可以使用字典数据结构来存储联系人信息,因为字典可以方便地关联姓名和电话号码等属性。下面是一个基础的例子:
```python
class ContactBook:
def __init__(self):
self.contacts = {}
def add_contact(self, name, phone_number):
"""
添加新的联系人
"""
if name in self.contacts:
print("该联系人已存在")
else:
self.contacts[name] = phone_number
print(f"成功添加了联系人 {name},电话号码: {phone_number}")
def find_contact(self, name):
"""
查找联系人
"""
if name in self.contacts:
return self.contacts[name]
else:
return None
def remove_contact(self, name):
"""
删除联系人
"""
if name in self.contacts:
del self.contacts[name]
print(f"成功删除了联系人 {name}")
else:
print("找不到该联系人")
# 使用示例
contact_book = ContactBook()
contact_book.add_contact("张三", "13800138000")
contact_book.find_contact("张三") # 输出: 13800138000
contact_book.remove_contact("李四") # 如果之前有李四这个联系人,会删除并打印消息
#
阅读全文
相关推荐


















