3 Hours

16. Hands-On Mini Projects

Module 16: Mini Projects

Building things that actually work

Welcome to the production forge. In this module, we transition from writing isolated code snippets to assembling complete, resilient, real-world Command Line Interface (CLI) applications. Each project demonstrates an architectural software pattern used in commercial systems.

CLI Architecture Pattern: The Event Loop & Dispatch Engine 1. TERMINAL INPUT input('Choose: ') 2. DEFENSIVE GUARD try / except ValueError 3. DISPATCH TABLE actions[choice]() DISK I/O json / csv Continuous while loop continues until user inputs 'quit' or exits

Project 1 — Calculator Program (Dispatch Table Pattern)

Software Pattern: First-Class Function Dispatching

Instead of building an unreadable 30-line if/elif/else ladder, professional engineers store function references directly inside a dictionary (a Dispatch Table). This turns branching logic into an instantaneous $O(1)$ hash table lookup.

A complete command-line calculator with zero-division protection:

Python 3
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
    if b == 0:
        raise ValueError('Cannot divide by zero')
    return a / b

# Function references stored as First-Class Citizens
operations = {'+': add, '-': subtract, '*': multiply, '/': divide}

def calculator():
    print('=== VoidX Math Engine ===')
    print('Available operations: +  -  *  /')
    
    while True:
        try:
            raw_a = input('First number (or "q" to quit): ').strip()
            if raw_a.lower() == 'q':
                print('Calculator closed.')
                break
            a = float(raw_a)
            
            op = input('Operation (+, -, *, /): ').strip()
            if op not in operations:
                print(f'Error: Unknown operator "{op}". Please choose +, -, *, or /.')
                continue
                
            b = float(input('Second number: '))
            
            # Dispatch table execution
            result = operations[op](a, b)
            print(f'Result: {a} {op} {b} = {result:.4f}\n')
        
        except ValueError as e:
            print(f'Input Error: {e}\n')
        except KeyboardInterrupt:
            print('\nSession terminated by user.')
            break

calculator()
Bonus Challenge: Add exponentiation (**) and modulo (%) to the operations dictionary without modifying any existing if statements.

Project 2 — To-Do List Application (JSON Persistence)

Software Pattern: Stateless to State-Persistent

When software closes, RAM is wiped. To survive application restarts, applications must serialize their in-memory data structures into permanent disk storage (JSON format).

A persistent to-do list CLI that saves state to your hard drive:

Python 3
import json
import os

FILE = 'todos.json'

def load_todos():
    """Safely loads tasks from disk if file exists."""
    if os.path.exists(FILE):
        with open(FILE, 'r', encoding='utf-8') as f:
            try:
                return json.load(f)
            except json.JSONDecodeError:
                return []
    return []

def save_todos(todos):
    """Persists tasks to permanent JSON storage."""
    with open(FILE, 'w', encoding='utf-8') as f:
        json.dump(todos, f, indent=2)

def show_todos(todos):
    if not todos:
        print('\n[No active tasks found in your list]\n')
        return
    print('\n--- Your Active Tasks ---')
    for i, task in enumerate(todos, 1):
        status = '[X]' if task['done'] else '[ ]'
        print(f'{i}. {status} {task["text"]}')
    print('-------------------------\n')

todos = load_todos()

while True:
    print('Menu: 1=List | 2=Add | 3=Complete | 4=Delete | 5=Quit')
    choice = input('Choose an action (1-5): ').strip()
    
    if choice == '1':
        show_todos(todos)
    elif choice == '2':
        text = input('New task description: ').strip()
        if text:
            todos.append({'text': text, 'done': False})
            save_todos(todos)
            print(f'✓ Added task: "{text}"')
    elif choice == '3':
        show_todos(todos)
        try:
            n = int(input('Task number to complete: ')) - 1
            if 0 <= n < len(todos):
                todos[n]['done'] = True
                save_todos(todos)
                print(f'✓ Marked task #{n+1} as complete!')
            else:
                print('Invalid task number.')
        except ValueError:
            print('Please enter a valid numeric index.')
    elif choice == '4':
        show_todos(todos)
        try:
            n = int(input('Task number to delete: ')) - 1
            if 0 <= n < len(todos):
                removed = todos.pop(n)
                save_todos(todos)
                print(f'✓ Deleted: "{removed["text"]}"')
            else:
                print('Invalid task number.')
        except ValueError:
            print('Please enter a valid numeric index.')
    elif choice == '5':
        print('All tasks safely saved to disk. Goodbye!')
        break
Bonus Challenge: Add a priority key (High, Medium, Low) to each task and allow filtering by priority.

Project 3 — Number Guessing Game (Binary Search Intuition)

Algorithmic Insight: Logarithmic Search

With 7 attempts between 1 and 100, guessing sequentially has a 7% chance of success. But using binary search (guessing the midpoint 50, then 75 or 25), you eliminate half the search space every single turn: $log_2(100) approx 6.64$ attempts, guaranteeing victory!

Python 3
import random

def number_game(min_val=1, max_val=100, max_attempts=7):
    secret = random.randint(min_val, max_val)
    attempts = 0
    
    print('========================================')
    print(f'Guess the secret number between {min_val} and {max_val}!')
    print(f'You have {max_attempts} attempts. Use binary search!')
    print('========================================')
    
    while attempts < max_attempts:
        try:
            guess = int(input(f'Attempt {attempts+1}/{max_attempts}: '))
        except ValueError:
            print('Invalid input. Please enter a whole integer.')
            continue
        
        attempts += 1
        
        if guess < secret:
            print('▲ Too low! Aim higher.')
        elif guess > secret:
            print('▼ Too high! Aim lower.')
        else:
            print(f'\n🎯 BINGO! You cracked it in {attempts} attempt(s)!')
            return
            
    print(f'\nGame over! The secret number was {secret}. Better luck next round!')

number_game()

Project 4 — Simple File-Based Project (CSV Grade Analytics)

Software Pattern: Tabular Stream Processing

Commercial data pipelines operate on tabular CSV records. This project demonstrates reading, writing, and analytical lambda sorting on structured disk files.

Python 3
import csv

def add_student(name, scores):
    """Calculates student metrics and appends row to CSV file."""
    avg = sum(scores) / len(scores)
    grade = 'A' if avg >= 90 else 'B' if avg >= 80 else 'C' if avg >= 70 else 'F'
    with open('grades.csv', 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow([name, *scores, f'{avg:.1f}', grade])
    print(f'✓ Recorded {name} — Average: {avg:.1f} ({grade})')

def show_top_students(n=3):
    """Reads grades.csv and prints top N performers sorted by average."""
    try:
        with open('grades.csv', 'r', encoding='utf-8') as f:
            rows = list(csv.reader(f))
        # Sort by average score (column index -2) descending
        sorted_rows = sorted(rows, key=lambda r: float(r[-2]), reverse=True)
        print(f'\nTop {min(n, len(sorted_rows))} Academic Performers:')
        for rank, row in enumerate(sorted_rows[:n], 1):
            print(f'  {rank}. {row[0]}: Average {row[-2]} (Grade {row[-1]})')
    except FileNotFoundError:
        print('No student data recorded yet.')

# Initialize test dataset
add_student('Ama', [95, 88, 92, 90])
add_student('Kofi', [78, 82, 75, 80])
add_student('Abena', [99, 95, 98, 97])
show_top_students(3)
Bonus Challenge: Add a function class_average() that reads all rows and calculates the mean score across the entire school.

Knowledge Check

Ready to test your understanding of 16. Hands-On Mini Projects?

Back