← Lesson 23

Lesson 24 · Python

Mini programs

~40 min

1. Mini Programs in Python

Building Mini Programs is the single best way to bridge the gap between learning Python syntax and becoming a confident software developer. A mini program combines core language concepts—variables, loops, conditional statements, functions, OOP, error handling, and file persistence—into a complete, working utility that solves a real-world problem.

Learning Objectives

  • Understand the core architectural loop of interactive command-line interface (CLI) applications.
  • Master modular program structure using the if __name__ == '__main__': entry point.
  • Handle user input cleanly and build crash-resilient code using try-except blocks.
  • Persist mini program data locally using built-in modules like json and csv.
  • Leverage standard library modules like random, math, and datetime to build useful utilities.

2. Anatomy of a Python Mini Program

Every interactive mini program follows a predictable life cycle pattern: Initialize → Main Loop (Input/Process/Output) → Exit & Persist. Structuring your script around this loop ensures your application runs smoothly without crashing on invalid user input.

The Core Application Loop Architecture:

import sys

def display_menu():
    print("\n=== MINI PROGRAM MENU ===")
    print("1. Perform Action")
    print("2. Exit Program")

def main():
    # 1. State Initialization
    running = True

    # 2. Main Application Loop
    while running:
        display_menu()
        choice = input("Enter your choice (1-2): ").strip()

        if choice == "1":
            print("Action executed successfully!")
        elif choice == "2":
            print("Thank you for using the program. Goodbye!")
            running = False  # Break loop
        else:
            print("Invalid choice! Please select 1 or 2.")

# Standard Python Execution Guard
if __name__ == "__main__":
    main()

3. Common Categories of Mini Programs

Depending on what task you want to solve, Python mini programs generally fall into four practical archetypes:

Category Core Features Key Python Modules Used Real-World Examples
CLI Utilities Menu loops, state storage, text formatting json, sys, dataclasses Task Manager, Expense Tracker
Generators & Tools Algorithmic logic, string manipulation, randomness random, string, secrets Password Generator, QR Code Maker
Interactive Games Randomized state, score tracking, win/loss logic random, time Number Guessing Game, Tic-Tac-Toe
System Automation File system reading/writing, batch processing os, shutil, pathlib File Organizer, Batch File Renamer

4. Essential Pattern 1: Secure Password Generator

This utility demonstrates using Python's built-in random and string modules to generate cryptographically random passwords tailored to user constraints.

Python code example:

import random
import string

def generate_password(length=12, use_digits=True, use_special=True):
    # Base character set: lowercase and uppercase letters
    characters = string.ascii_letters
    
    if use_digits:
        characters += string.digits
    if use_special:
        characters += string.punctuation

    # Randomly select characters from the combined pool
    password = "".join(random.choice(characters) for _ in range(length))
    return password

# Main execution loop
print("=== Secure Password Generator ===")
try:
    user_length = int(input("Enter desired password length (min 6): "))
    if user_length < 6:
        print("Length too short! Defaulting to 12 characters.")
        user_length = 12

    pwd = generate_password(length=user_length)
    print(f"\nGenerated Password: {pwd}")
except ValueError:
    print("Invalid input! Please enter a valid numerical integer.")

5. Essential Pattern 2: Interactive To-Do List with JSON Storage

A complete, crash-resilient CLI application that allows users to create, view, complete, and save tasks locally to a JSON file on disk.

Python code example:

import json
import os

DATA_FILE = "tasks.json"

def load_tasks():
    """Load tasks from disk if file exists."""
    if os.path.exists(DATA_FILE):
        with open(DATA_FILE, "r") as file:
            try:
                return json.load(file)
            except json.JSONDecodeError:
                return []
    return []

def save_tasks(tasks):
    """Save tasks to disk as JSON format."""
    with open(DATA_FILE, "w") as file:
        json.dump(tasks, file, indent=4)

def run_todo_app():
    tasks = load_tasks()

    while True:
        print("\n--- TO-DO MANAGER ---")
        print("1. View Tasks")
        print("2. Add Task")
        print("3. Mark Task Complete")
        print("4. Save & Exit")

        choice = input("Select an option (1-4): ").strip()

        if choice == "1":
            if not tasks:
                print("Your task list is empty!")
            else:
                for idx, task in enumerate(tasks, start=1):
                    status = "✓" if task["done"] else "✗"
                    print(f"{idx}. [{status}] {task['title']}")

        elif choice == "2":
            title = input("Enter task title: ").strip()
            if title:
                tasks.append({"title": title, "done": False})
                print(f"Task '{title}' added!")

        elif choice == "3":
            if not tasks:
                print("No tasks available to mark complete.")
                continue
            try:
                task_num = int(input("Enter task number to complete: "))
                if 1 <= task_num <= len(tasks):
                    tasks[task_num - 1]["done"] = True
                    print("Task marked as completed!")
                else:
                    print("Invalid task number.")
            except ValueError:
                print("Please enter a valid integer!")

        elif choice == "4":
            save_tasks(tasks)
            print("Tasks saved. Goodbye!")
            break

        else:
            print("Invalid selection. Try again.")

if __name__ == "__main__":
    run_todo_app()

6. Essential Pattern 3: Automated File Organizer Script

This script uses Python's standard library pathlib module to scan a directory and automatically sort files into categorized folders based on their file extension.

from pathlib import Path
import shutil

def organize_folder(folder_path):
    target_dir = Path(folder_path)
    
    if not target_dir.exists():
        print(f"Error: Path '{folder_path}' does not exist.")
        return

    # Categorization mapping based on file extension
    CATEGORIES = {
        "Images": [".jpg", ".jpeg", ".png", ".gif", ".svg"],
        "Documents": [".pdf", ".docx", ".txt", ".xlsx", ".pptx"],
        "Code": [".py", ".html", ".css", ".js", ".json"],
        "Archives": [".zip", ".tar", ".gz", ".7z"]
    }

    # Iterate over all files in target folder
    for file in target_dir.iterdir():
        if file.is_file():
            ext = file.suffix.lower()
            moved = False

            for category, extensions in CATEGORIES.items():
                if ext in extensions:
                    dest_dir = target_dir / category
                    dest_dir.mkdir(exist_ok=True)  # Create category folder if missing
                    shutil.move(str(file), str(dest_dir / file.name))
                    print(f"Moved: {file.name} -> {category}/")
                    moved = True
                    break

            # Unrecognized files go to an 'Others' folder
            if not moved:
                dest_dir = target_dir / "Others"
                dest_dir.mkdir(exist_ok=True)
                shutil.move(str(file), str(dest_dir / file.name))

# Example invocation:
# organize_folder("./Downloads")

7. Common Beginner Mistakes

⚠️ Watch out for these mistakes:

  • Unchecked User Input (Crashing on Type Conversion): Calling int(input()) directly without wrapping it in a try-except ValueError block will instantly crash your CLI program if a user types text instead of digits!
  • Creating Infinite Loops Without Exit Paths: Writing while True: without clear break statements or loop termination flags makes programs lock up indefinitely.
  • Hardcoding File Paths: Hardcoding absolute paths like C:\Users\Alice\Documents\file.txt prevents your mini program from working on other machines or operating systems. Use relative paths or pathlib.Path.
  • Forgetting to Save File Changes On Exit: Always ensure write operations (like saving JSON data) occur when the user explicitly chooses to exit or after major state updates.

8. Code Examples

Here is an example of an interactive Unit & Temperature Converter built with clean input validation functions:

# Unit Converter Mini Program

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
    return (fahrenheit - 32) * 5/9

def get_float_input(prompt):
    """Helper function to guarantee valid numeric input."""
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Invalid input! Please enter a valid number.")

def main_converter():
    print("=== Temperature Converter ===")
    print("1. Celsius to Fahrenheit")
    print("2. Fahrenheit to Celsius")
    
    choice = input("Choose conversion type (1 or 2): ").strip()

    if choice == "1":
        c = get_float_input("Enter temperature in °C: ")
        f = celsius_to_fahrenheit(c)
        print(f"Result: {c:.2f}°C = {f:.2f}°F")
    elif choice == "2":
        f = get_float_input("Enter temperature in °F: ")
        c = fahrenheit_to_celsius(f)
        print(f"Result: {f:.2f}°F = {c:.2f}°C")
    else:
        print("Invalid conversion choice selected.")

if __name__ == "__main__":
    main_converter()
Interactive Practice

Mini Practice: Number Guessing Game

Create a mini guessing game using random.randint(1, 100). Use a while loop to ask the user for guesses and give feedback ("Too high!", "Too low!") until they guess correctly.

0% complete
Check when done
Quiz

Test Your Understanding

1. What is the main benefit of wrapping top-level execution code inside `if __name__ == "__main__":`?

2. Which built-in Python module is commonly used to save structured application data (like tasks or user profiles) directly to a text file?

3. What exception is raised when calling `int("abc")` on invalid user string input?

4. How do you prevent a program from crashing when opening a file that might not exist on disk?

9. Challenge Project

Personal Expense Tracker CLI: Build an interactive CLI program to track daily finances:

  1. Create a menu system with choices: Add Expense, View Summary, Filter by Category, and Save & Exit.
  2. Store expenses as dictionaries inside a list: {"amount": 15.50, "category": "Food", "description": "Lunch"}.
  3. Implement a function to calculate total money spent across all recorded expenses.
  4. Save all expense records to a file named expenses.json using the json module so data persists between runs!

10. Key Takeaways

  • Mini programs integrate all Python basics (loops, logic, functions, OOP) into functional software.
  • Build resilient application loops using while loops and input validation with try-except.
  • Structure your code cleanly using functions and protect entry points with if __name__ == '__main__':.
  • Persist data locally on disk using built-in format modules like json or csv.
  • Leverage Python standard library modules like random, pathlib, and os for real-world automation.

🚀 Progression

You've mastered Mini Programs! Next up, we will explore **File Handling & Modules in Python** to scale up your application development!