Exercise 5.2
← Previous Module 5: Dictionaries & Sets Next →
Statement
Solution

Python Exercise 5.2: Phonebook

Create a dictionary-based phonebook with Add, Search, Delete menu.

Your program should:

  • Use a dictionary to store contact names as keys and phone numbers as values.
  • Display a menu with options: 1. Add Contact, 2. Search Contact, 3. Delete Contact, 4. Exit.
  • For Add: prompt for name and phone number, add to dictionary.
  • For Search: prompt for name, display phone number if found, else "Contact not found".
  • For Delete: prompt for name, remove if exists, else "Contact not found".
  • Continue looping until user chooses Exit.

Sample Interaction:

Input
Output
1 John Doe 123-456-7890 2 John Doe 3 Jane Doe 4
Contact added. Phone: 123-456-7890 Contact not found. Exiting...

Solution

Here is one way to implement a phonebook using a dictionary.

# Phonebook dictionary phonebook = {} while True: print("1. Add Contact") print("2. Search Contact") print("3. Delete Contact") print("4. Exit") choice = input("Choose an option: ") if choice == "1": name = input("Enter name: ") phone = input("Enter phone number: ") phonebook[name] = phone print("Contact added.") elif choice == "2": name = input("Enter name to search: ") if name in phonebook: print(f"Phone: {phonebook[name]}") else: print("Contact not found.") elif choice == "3": name = input("Enter name to delete: ") if name in phonebook: del phonebook[name] print("Contact deleted.") else: print("Contact not found.") elif choice == "4": print("Exiting...") break else: print("Invalid choice.")

Key Concepts:

  • dict is used for key-value storage of contacts.
  • in operator checks if a key exists in the dictionary.
  • del removes a key-value pair from the dictionary.
  • Infinite while True loop with break for menu system.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top