Menu
CoddyTech

列出所有联系人

本课属于 Coddy Python 学习旅程的“逻辑与流程”单元。第 22 课,共 78 课。

challenge icon

挑战

简单

下一步是创建 list_all_contacts 函数。此函数允许用户查看通讯录中存储的所有联系人及其详细信息。


你的任务:

  1. 创建一个名为 list_all_contacts 的函数,它接受一个参数:contact_book(一个字典)。
  2. 检查 contact_book 是否为空:
    • 如果为空,打印:"No contacts available."。
  3. 如果不为空:
    • 循环遍历字典中的每个联系人,并以易读的格式打印他们的姓名、电话、电子邮件和地址。

预期行为:

对于包含以下内容的 contact_book:

{
    "Alice": {"phone": "123-456-7890", "email": "alice@example.com", "address": "123 Main St"},
    "Bob": {"phone": "234-567-8901", "email": "bob@example.com", "address": "456 Oak Ave"}
}

输出应为:

Name: Alice
Phone: 123-456-7890
Email: alice@example.com
Address: 123 Main St

Name: Bob
Phone: 234-567-8901
Email: bob@example.com
Address: 456 Oak Ave

亲手试试

def display_menu():
    print("Contact Book Menu:")
    print("1. Add Contact")
    print("2. View Contact")
    print("3. Edit Contact")
    print("4. Delete Contact")
    print("5. List All Contacts")
    print("6. Exit")

def add_contact(contact_book):
    name = input()
    if name in contact_book:
        print("Contact already exists!")
        return
    phone = input()
    email = input()
    address = input()
    contact_book[name] = {"phone": phone, "email": email, "address": address}
    print("Contact added successfully!")

def view_contact(contact_book):
    name = input()
    if name in contact_book:
        contact = contact_book[name]
        print(f"Name: {name}")
        print(f"Phone: {contact['phone']}")
        print(f"Email: {contact['email']}")
        print(f"Address: {contact['address']}")
    else:
        print("Contact not found!")

def edit_contact(contact_book):
    name = input()
    if name in contact_book:
        phone = input()
        email = input()
        address = input()

        if phone == '':
            phone = contact_book[name]['phone']
        if email == '':
            email = contact_book[name]['email']
        if address == '':
            address = contact_book[name]['address']

        contact_book[name] = {"phone": phone, "email": email, "address": address}
        print("Contact updated successfully!")
    else:
        print("Contact not found!")

def delete_contact(contact_book):
    name = input()
    if name in contact_book:
        del contact_book[name]
        print("Contact deleted successfully!")
    else:
        print("Contact not found!")

逻辑与流程中的所有课

自己练习: Python 在线编译器