Python Contact Book Example

A small contact book project is a great way to practice Python basics.

In this example, you will build a simple command-line program that:

  • stores contact names and phone numbers
  • asks the user for input
  • searches for contacts
  • deletes contacts
  • repeats with a menu until the user exits

This project is beginner-friendly because it uses a few core ideas in a practical way.

What this project builds

This example creates:

  • A simple command-line contact book
  • A program that stores contact names and phone numbers
  • A menu that lets the user add, view, search, and delete contacts
  • A good beginner project for practicing dictionaries and loops

Skills this example practices

While building this project, you will practice:

  • Using a dictionary to store related data
  • Using a while loop for a repeating menu
  • Using input() to get user input
  • Using if and elif to handle menu options
  • Checking if a key exists before reading or deleting it

How the contact data is stored

The program uses a dictionary named contacts.

  • Each key is a contact name
  • Each value is that contact's phone number

Example:

contacts = {
    "Alice": "1234567890",
    "Bob": "5551234567"
}

This keeps the project simple and easy to understand.

If you are new to dictionaries, see Python dictionaries explained.

Build the menu step by step

The basic idea is:

  1. Start with an empty dictionary
  2. Use while True to keep showing the menu
  3. Read the user's choice with input()
  4. Run different code based on the choice
  5. Use break to exit

Here is the full working script:

contacts = {}

while True:
    print("\n1. Add contact")
    print("2. View contacts")
    print("3. Search contact")
    print("4. Delete contact")
    print("5. Exit")

    choice = input("Choose an option: ")

    if choice == "1":
        name = input("Name: ")
        phone = input("Phone: ")
        contacts[name] = phone
        print("Contact saved.")

    elif choice == "2":
        if not contacts:
            print("No contacts found.")
        else:
            for name, phone in contacts.items():
                print(name, "-", phone)

    elif choice == "3":
        name = input("Enter name to search: ")
        if name in contacts:
            print(name, "-", contacts[name])
        else:
            print("Contact not found.")

    elif choice == "4":
        name = input("Enter name to delete: ")
        if name in contacts:
            del contacts[name]
            print("Contact deleted.")
        else:
            print("Contact not found.")

    elif choice == "5":
        print("Goodbye!")
        break

    else:
        print("Invalid option.")

How this works

  • contacts = {} creates an empty dictionary
  • while True: creates a loop that keeps running
  • choice = input(...) reads the menu option
  • if, elif, and else decide which action to run
  • break stops the loop when the user chooses to exit

Add a new contact

To add a contact, ask for the name and phone number, then save it in the dictionary.

name = input("Name: ")
phone = input("Phone: ")
contacts[name] = phone
print("Contact saved.")

Key line:

contacts[name] = phone

This stores the phone number under the contact name.

Example:

contacts["Alice"] = "1234567890"

After that, the dictionary becomes:

{"Alice": "1234567890"}

One important detail: if the same name is added again, the old phone number is replaced. That happens because dictionary keys must be unique.

View all contacts

To show all contacts, first check whether the dictionary is empty.

if not contacts:
    print("No contacts found.")
else:
    for name, phone in contacts.items():
        print(name, "-", phone)

This does two things:

  • if not contacts: checks whether the dictionary is empty
  • contacts.items() gives you each name and phone number pair

If you want more help with this pattern, see how to loop through a dictionary in Python and the dict.items() method reference.

Example output:

Alice - 1234567890
Bob - 5551234567

Search for a contact safely

When searching, do not directly use contacts[name] unless you know the name exists.

Use a key check first:

name = input("Enter name to search: ")

if name in contacts:
    print(name, "-", contacts[name])
else:
    print("Contact not found.")

This avoids a KeyError.

Why this matters:

  • If the name exists, you can safely read the phone number
  • If the name does not exist, the program prints a clear message instead of crashing

If you want more detail, see how to check if a key exists in a dictionary in Python and KeyError in Python: causes and fixes.

Delete a contact safely

Deleting follows the same idea as searching.

Check first, then delete:

name = input("Enter name to delete: ")

if name in contacts:
    del contacts[name]
    print("Contact deleted.")
else:
    print("Contact not found.")

Key line:

del contacts[name]

This removes the contact from the dictionary, but only if the name exists.

Common beginner improvements

Once the basic version works, you can improve it in simple ways:

  • Store more than one field per contact
  • Use nested dictionaries for phone and email
  • Make name search case-insensitive
  • Sort contacts before printing
  • Save contacts to a file later

For example, a contact could look like this:

contacts = {
    "Alice": {
        "phone": "1234567890",
        "email": "alice@example.com"
    }
}

A useful next step is saving your contacts to a JSON file. See how to parse JSON in Python.

Beginner debugging tips

If your program does not behave as expected, test one small part at a time.

Helpful debug lines:

print(contacts)
print(choice)
print(type(choice))
print(name in contacts)
for name, phone in contacts.items():
    print(name, phone)

These can help you check:

  • whether contacts are being stored correctly
  • what the user actually entered
  • whether choice is a string
  • whether a name exists in the dictionary
  • whether the loop is reading your data correctly

Common mistakes

Here are some common beginner problems in this project.

Using contacts[name] before checking if the name exists

This can raise a KeyError.

Problem example:

name = input("Enter name: ")
print(contacts[name])

Safer version:

if name in contacts:
    print(contacts[name])
else:
    print("Contact not found.")

Forgetting that input() returns a string

This is a very common issue.

Problem example:

choice = input("Choose an option: ")

if choice == 1:
    print("Add contact")

This does not match because choice is a string, not a number.

Correct version:

if choice == "1":
    print("Add contact")

You can confirm this with:

print(type(choice))

Indentation mistakes inside the while loop

Python uses indentation to define blocks of code.

For example, this is wrong:

while True:
print("Menu")

This causes an indentation error.

Correct version:

while True:
    print("Menu")

If you see this problem, read IndentationError: expected an indented block.

Overwriting a contact by using the same name again

This is valid Python behavior, but beginners sometimes do not expect it.

Example:

contacts["Alice"] = "1111111111"
contacts["Alice"] = "2222222222"

print(contacts)

Output:

{'Alice': '2222222222'}

The second value replaces the first one.

Using contacts.items instead of contacts.items()

This is another common mistake.

Wrong:

for name, phone in contacts.items:
    print(name, phone)

Correct:

for name, phone in contacts.items():
    print(name, phone)

The parentheses are required because items() is a method.

FAQ

Why is a dictionary used for this project?

A dictionary lets you look up a contact by name quickly and keeps the example simple.

What happens if I add the same name twice?

The new phone number replaces the old value because dictionary keys must be unique.

Can I store email addresses too?

Yes. A good next step is to store each contact as a nested dictionary with fields like phone and email.

Why does my menu choice not match?

input() returns text, so compare against string values like "1" instead of the number 1.

How can I save contacts after the program closes?

A good next improvement is saving the dictionary to a file, such as JSON.

See also

After you build the basic contact book, try improving it by adding email fields, duplicate checks, sorting, and file saving with JSON.