Python实现手机通讯录基本功能
时间: 2024-04-25 07:19:45 浏览: 164
Python可以通过使用字典(Dictionary)数据结构来实现手机通讯录的基本功能。字典是Python中的一种键值对(key-value)数据结构,可以用来存储联系人的姓名和电话号码。
以下是一个简单的Python代码示例,实现了手机通讯录的基本功能:
```python
# 创建一个空的通讯录字典
phonebook = {}
# 添加联系人
def add_contact(name, phone_number):
phonebook[name] = phone_number
print("联系人已添加成功!")
# 查找联系人
def search_contact(name):
if name in phonebook:
print("联系人:", name)
print("电话号码:", phonebook[name])
else:
print("联系人不存在!")
# 删除联系人
def delete_contact(name):
if name in phonebook:
del phonebook[name]
print("联系人已删除成功!")
else:
print("联系人不存在!")
# 显示所有联系人
def display_contacts():
if len(phonebook) == 0:
print("通讯录为空!")
else:
print("所有联系人:")
for name, phone_number in phonebook.items():
print(name, ":", phone_number)
# 测试代码
add_contact("张三", "123456789")
add_contact("李四", "987654321")
search_contact("张三")
delete_contact("李四")
display_contacts()
```
以上代码实现了添加联系人、查找联系人、删除联系人和显示所有联系人的功能。你可以根据需要进行扩展和修改。
阅读全文
相关推荐
















