Python
Topic 17 · Writing real programs

Your First Projects: Three Small Programs

Put everything together in three complete programs: a number-guessing game, a to-do list that saves to a file, and an expense tracker that summarises a CSV. Plan, build step by step, test and extend each one.

Show:
In this topic
Beginner

How to build a program from nothing

Knowing the pieces (variables, loops, functions, files) is different from building a whole program. Professionals follow roughly the same steps every time, and you should too:

  1. Describe it in plain words. What goes in, what comes out, what happens in between.
  2. Break it into small steps, each simple enough to be one function.
  3. Build one step at a time, and run it after every few lines. Never write 100 lines and then run it for the first time.
  4. Test with normal, edge and wrong inputs (an empty list, a zero, text where a number should be).
  5. Tidy up: clear names, docstrings, remove dead code. Then add features.

Each project below follows these steps. Run it, read it, then try the extension ideas: changing a working program is how you learn to write your own.

Beginner

Project 1: the number-guessing game

In plain words: the computer picks a secret number from 1 to 100. The player guesses; after each guess the computer says "too high" or "too low", until they get it. It reports how many guesses it took.

Steps: pick the number (random); repeat (a while loop): get a guess, compare it (if/elif/else), count it; stop when it is right (break). One extra step makes it robust: check the guess is a number before using it.

Because nobody can type into this page, the version below gets its answers from a list. To play it yourself, press Open in playground, change the last lines as the comment says, and type one guess per line in the Program input box before pressing Run.

Python
import random

def read_guess(text):
    """Turn the player's text into a number from 1 to 100, or None if it is not valid."""
    text = text.strip()
    if not text.isdigit():
        return None
    n = int(text)
    if 1 <= n <= 100:
        return n
    return None

def check(guess, secret):
    if guess < secret:
        return "too low"
    if guess > secret:
        return "too high"
    return "correct"

def play(secret, ask):
    """Play one game. ask() gets the player's next answer as text."""
    tries = 0
    while True:
        guess = read_guess(ask())
        if guess is None:
            print("Please type a whole number from 1 to 100.")
            continue
        tries += 1
        result = check(guess, secret)
        print(guess, "is", result)
        if result == "correct":
            print(f"You got it in {tries} guesses!")
            return tries

random.seed(7)
secret = random.randint(1, 100)

# Nobody can type into this page, so a list of answers stands in for the player.
# Notice "abc" and "500": the game handles them without crashing.
answers = iter(["50", "abc", "25", "37", "500", "43", "40", "41", "42"])
play(secret, lambda: next(answers))

# To play it yourself in the playground, replace the last two lines with:
# play(random.randint(1, 100), lambda: input("Your guess (1-100): "))
Open in playground ↗
Beginner

Project 2: a to-do list that remembers

In plain words: keep a list of tasks; add tasks, mark them done, show them, and save them to a file so they are still there next time.

Steps: store tasks as a list of dictionaries ({"title": …, "done": False}); one small function per action; save and load with JSON. Notice how short each function is, and how the last part just calls them in order: that is what well-organised code looks like.

Python
import json
from pathlib import Path

FILE = Path("todo.json")

def load():
    """Read the saved tasks, or start empty if there is no file yet."""
    if FILE.exists():
        return json.loads(FILE.read_text(encoding="utf-8"))
    return []

def save(tasks):
    FILE.write_text(json.dumps(tasks, indent=2), encoding="utf-8")

def add(tasks, title):
    tasks.append({"title": title, "done": False})

def complete(tasks, number):
    """Mark task number (starting at 1) as done. Returns False if there is no such task."""
    if 1 <= number <= len(tasks):
        tasks[number - 1]["done"] = True
        return True
    return False

def show(tasks):
    if not tasks:
        print("Nothing to do!")
    for i, t in enumerate(tasks, start=1):
        mark = "x" if t["done"] else " "
        print(f"{i}. [{mark}] {t['title']}")
    left = sum(1 for t in tasks if not t["done"])
    print(f"{left} of {len(tasks)} left\n")

# --- using it ---
FILE.unlink(missing_ok=True)       # start fresh for this demo
tasks = load()
add(tasks, "Finish the loops lesson")
add(tasks, "Practise 3 exercises")
add(tasks, "Install Python")
complete(tasks, 1)
save(tasks)
show(tasks)

tasks_again = load()               # as if the program had restarted
complete(tasks_again, 3)
show(tasks_again)
print(complete(tasks_again, 9))    # no task 9: handled, no crash
Open in playground ↗
Beginner

Project 3: an expense tracker

In plain words: read a CSV of spending (date, category, amount), and report the total, the total per category with a percentage, the biggest single expense and the spending per month.

Steps: read the CSV (csv.DictReader, converting amounts to float); group with a dictionary; format a neat report with f-strings. This is exactly what a data analyst does, and in the pandas lesson you will see the same report in a few lines.

Python
import csv
from collections import defaultdict

# create a sample file (in real life you would export this from your bank or a spreadsheet)
sample = """date,category,amount
2026-10-02,groceries,84.20
2026-10-05,transport,30.00
2026-10-09,eating out,42.50
2026-10-15,groceries,61.75
2026-10-28,rent,450.00
2026-11-01,groceries,93.10
2026-11-03,transport,30.00
2026-11-08,eating out,18.90
2026-11-12,rent,450.00
2026-11-14,books,35.95
"""
with open("expenses.csv", "w", encoding="utf-8") as f:
    f.write(sample)

def read_expenses(path):
    with open(path, newline="", encoding="utf-8") as f:
        return [{"date": r["date"], "category": r["category"], "amount": float(r["amount"])}
                for r in csv.DictReader(f)]

def total_by(expenses, key):
    totals = defaultdict(float)
    for e in expenses:
        totals[key(e)] += e["amount"]
    return dict(totals)

expenses = read_expenses("expenses.csv")
grand = sum(e["amount"] for e in expenses)
print(f"{len(expenses)} expenses, total ${grand:,.2f}\n")

print("By category:")
cats = total_by(expenses, key=lambda e: e["category"])
for cat, amount in sorted(cats.items(), key=lambda kv: kv[1], reverse=True):
    print(f"  {cat:<12} ${amount:>8,.2f}  {amount / grand:>6.1%}")

print("\nBy month:")
for month, amount in sorted(total_by(expenses, key=lambda e: e["date"][:7]).items()):
    print(f"  {month}  ${amount:>8,.2f}")

biggest = max(expenses, key=lambda e: e["amount"])
print(f"\nBiggest: ${biggest['amount']:.2f} on {biggest['category']} ({biggest['date']})")
Open in playground ↗
Beginner

Extend the projects

Changing a working program is the best practice there is. Try these, one at a time, running after each change:

  • Guessing game: limit the player to 7 guesses; let them choose an easy (1–50) or hard (1–1000) level; keep a best score in a file.
  • To-do list: add a delete(tasks, number) function; add a due date to each task and show overdue tasks first (use datetime).
  • Expense tracker: add a monthly budget per category and print a warning when it is exceeded; skip rows with a missing or invalid amount instead of crashing (use try/except).

When you have done one, put it on your computer (see Set up Python) and run it from the terminal: that is a real program you wrote.

Beginner

Practice: check yourself

Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.

Exercise 1. Is it a palindrome?

Write is_palindrome(text) that returns True when text reads the same backwards, ignoring capitals, spaces and punctuation. "Never odd or even" → True; "Python" → False.

Exercise 2. FizzBuzz

The classic interview warm-up. Print the numbers 1 to 20, but print Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both.

Beginner

Summary

Key words

requirements
a plain-words description of what a program must do
decomposition
breaking a problem into small steps, usually one function each
edge case
an unusual input that often breaks code: empty, zero, huge, wrong type
incremental development
building a little, running it, then building a little more

Common mistakes

  • Writing the whole program before running any of it.
  • One giant block of code instead of small functions with clear names.
  • Not testing what happens with bad input (empty answers, letters instead of numbers).
  • Keeping data only in variables, so it is lost when the program stops: save to a file.
Check yourself

Quiz

1. What is the best way to build a program?

2. Why does the to-do list store tasks as a list of dictionaries?

3. In the guessing game, why check that the input is a number before converting it?

Ready