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:
dictis used for key-value storage of contacts.inoperator checks if a key exists in the dictionary.delremoves a key-value pair from the dictionary.- Infinite
while Trueloop withbreakfor menu system.
Test Console
Run code to see output...