Tutorials / Python Basics / Lesson 15

Putting It All Together — Build a Simple CLI App

What You Will Build

In this final lesson, you will build a complete contact book application from scratch. It will:

  • Store contacts (name + phone number + email)
  • Let you add, view, search, and delete contacts
  • Save everything to a file so data persists between runs
  • Handle errors gracefully

This project uses everything you have learned: variables, data types, strings, input, if statements, loops, functions, lists, dictionaries, files, and error handling.


Project Structure

Create a new file called contacts.py. We will build it section by section.


Step 1: File Storage Functions

import json

FILE = "contacts.json"

def load_contacts():
    """Load contacts from file. Return empty list if file doesn't exist."""
    try:
        with open(FILE, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        return []

def save_contacts(contacts):
    """Save contacts to file."""
    with open(FILE, "w") as f:
        json.dump(contacts, f, indent=2)
    print("Contacts saved.")

We use JSON instead of plain text because it handles structured data (like dictionaries) cleanly.


Step 2: Contact Operations

def add_contact(contacts):
    """Add a new contact."""
    print("\n-- Add Contact --")
    name = input("Name: ").strip()
    phone = input("Phone: ").strip()
    email = input("Email: ").strip()

    if not name:
        print("Name cannot be empty.")
        return

    contacts.append({
        "name": name,
        "phone": phone,
        "email": email,
    })
    save_contacts(contacts)
    print(f"Contact '{name}' added.")

def list_contacts(contacts):
    """Display all contacts."""
    print(f"\n-- Contacts ({len(contacts)}) --")
    if not contacts:
        print("No contacts yet.")
        return
    for i, contact in enumerate(contacts, 1):
        print(f"{i}. {contact['name']}")
        print(f"   Phone: {contact['phone']}")
        print(f"   Email: {contact['email']}")

def search_contacts(contacts):
    """Search for a contact by name."""
    print("\n-- Search --")
    query = input("Search name: ").strip().lower()
    results = [c for c in contacts if query in c["name"].lower()]

    if not results:
        print("No matching contacts.")
    else:
        for contact in results:
            print(f"\n{contact['name']}")
            print(f"  Phone: {contact['phone']}")
            print(f"  Email: {contact['email']}")

def delete_contact(contacts):
    """Delete a contact by number."""
    list_contacts(contacts)
    if not contacts:
        return

    try:
        num = int(input("\nDelete contact number: ")) - 1
        if 0 <= num < len(contacts):
            removed = contacts.pop(num)
            save_contacts(contacts)
            print(f"Deleted '{removed['name']}'.")
        else:
            print("Invalid number.")
    except ValueError:
        print("Please enter a valid number.")

Step 3: Main Menu

def show_menu():
    """Display the main menu."""
    print("\n=== Contact Book ===")
    print("1. List contacts")
    print("2. Add contact")
    print("3. Search contacts")
    print("4. Delete contact")
    print("5. Quit")

def main():
    contacts = load_contacts()
    print(f"Loaded {len(contacts)} contact(s).")

    while True:
        show_menu()
        choice = input("\nChoice: ").strip()

        if choice == "1":
            list_contacts(contacts)
        elif choice == "2":
            add_contact(contacts)
        elif choice == "3":
            search_contacts(contacts)
        elif choice == "4":
            delete_contact(contacts)
        elif choice == "5":
            print("Goodbye!")
            break
        else:
            print("Invalid choice. Enter 1-5.")

main()

Complete Program

Putting it all together, contacts.py is about 80 lines of clean, readable Python.

Run it:

python contacts.py

Example interaction:

Loaded 0 contact(s).

=== Contact Book ===
1. List contacts
2. Add contact
3. Search contacts
4. Delete contact
5. Quit

Choice: 2

-- Add Contact --
Name: Alice
Phone: 555-1234
Email: alice@example.com
Contacts saved.
Contact 'Alice' added.

=== Contact Book ===
...

Choice: 1

-- Contacts (1) --
1. Alice
   Phone: 555-1234
   Email: alice@example.com

What You Used in This Project

ConceptWhere it appeared
VariablesStoring contacts, file name
StringsNames, phone numbers, emails
ListsThe contacts collection
DictionariesEach individual contact
FunctionsOne function per operation
for loopsListing and searching contacts
if statementsMenu choices, validation
File I/OSaving and loading contacts
Error handlingInvalid input, file not found
f-stringsDisplaying contact information

What You Learned in This Course

You started from zero and now you can:

  • Write and run Python scripts
  • Store and manipulate data with variables, lists, and dictionaries
  • Control program flow with if statements and loops
  • Write reusable code with functions
  • Read and write files
  • Handle errors gracefully
  • Build a complete working application

This is a real foundation. From here, you can explore web development (Flask, Django), data analysis (pandas, numpy), automation, or anything else Python is used for. The blog on this site has deep dives into more advanced Python topics whenever you are ready.

Congratulations on completing Python Basics.