A contact book introduces CRUD operations: create, read, update, and delete. It also gives you a reason to think about normalising user input.
What you will build#
A menu-driven program that stores contacts in a dictionary keyed by name. Each contact holds a phone number and an email address.
1. Add contact
2. Search contact
3. List all contacts
4. Update contact
5. Delete contact
6. QuitData model#
contacts = {
"ada lovelace": {
"name": "Ada Lovelace",
"phone": "555-0101",
"email": "ada@example.com",
},
"grace hopper": {
"name": "Grace Hopper",
"phone": "555-0102",
"email": "grace@example.com",
},
}The key is the lowercased name, which makes lookups case-insensitive. The stored name preserves the capitalisation the user typed. This is a small but useful separation between identity and display.
Normalisation helpers#
def normalise_name(name):
return " ".join(name.strip().lower().split())
def display_name(name):
return " ".join(name.strip().split())" ".join(text.split()) collapses repeated spaces. That prevents Ada Lovelace and ada lovelace from becoming separate contacts.
Add a contact#
def add_contact():
raw_name = input("Full name: ")
key = normalise_name(raw_name)
if not key:
print("A name is required.")
return
if key in contacts:
print("That contact already exists.")
return
phone = input("Phone: ").strip()
email = input("Email: ").strip()
contacts[key] = {
"name": display_name(raw_name),
"phone": phone,
"email": email,
}
print("Contact added.")Decide which fields are required. At minimum, require a name. If you want to validate email, keep it simple and explain the limitation; a full email grammar is complex.
Search#
def search_contacts():
query = normalise_name(input("Search name: "))
matches = [
contact for key, contact in contacts.items()
if query in key
]
if not matches:
print("No matching contacts.")
return
for contact in matches:
print_contact(contact)This performs a substring search, so ada finds ada lovelace. It scans every contact; that is fine for a few hundred entries. A real application would use a database index.
Display#
def print_contact(contact):
print(f"Name: {contact['name']}")
print(f"Phone: {contact['phone'] or '-'}")
print(f"Email: {contact['email'] or '-'}")
print()Use dict.get() if older records might miss a field. For example, contact.get("email", "-") avoids KeyError when the schema changes.
Update and delete#
Both operations need the same lookup and existence check:
def find_contact():
key = normalise_name(input("Contact name: "))
contact = contacts.get(key)
if contact is None:
print("Contact not found.")
return key, contactFor update, keep the old value when the user enters a blank line:
phone = input("New phone (blank to keep): ").strip()
if phone:
contact["phone"] = phoneFor delete, confirm first:
confirmation = input("Type yes to delete: ").strip().lower()
if confirmation == "yes":
del contacts[key]
print("Contact deleted.")
else:
print("Delete cancelled.")Main loop#
actions = {
"1": add_contact,
"2": search_contacts,
"3": list_contacts,
"4": update_contact,
"5": delete_contact,
}
while True:
show_menu()
choice = input("Choose: ").strip()
if choice == "6":
break
action = actions.get(choice)
if action is None:
print("Invalid choice.")
else:
action()Testing checklist#
- Add two contacts and list them.
- Search with different capitalisation.
- Add a duplicate name and verify it is rejected.
- Update a phone number and cancel an update with a blank line.
- Delete a contact after confirmation.
- Try to delete a missing contact.
- Check that repeated spaces in names do not create duplicates.
Stretch goals#
- Add a second phone number field.
- Export contacts as JSON with
json.dumps(contacts, indent=2). - Sort listings by display name with
sorted(contacts.values(), key=lambda contact: contact["name"]). - Group contacts by first letter.
- Add a fuzzy search that ignores case and punctuation.
