π‘ 50 Python Project Ideas
in Python
50 Python project ideas in eight themes, each with a goal, skills practised, feature checklist and stretch goal, plus a runnable starter project for every theme.
What this lesson is about
Almost everyone who learns Python hits the same wall: you finish a course, you understand loops and functions, and then a blank editor stares back and you have no idea what to build. Tutorials hand you the next step; real projects do not. This page is my answer to that wall. It is a curated list of about fifty concrete project ideas, each small enough to finish and specific enough to start today.
Every idea follows the same pattern so you can compare them quickly. There is a goal (what the finished program does), the skills practised (what you will have to learn or revise), a feature checklist (what counts as done) and a stretch goal (the next step once the basics work). The ideas are grouped into eight themes: command-line tools, text and files, web and APIs, data, automation, games, AI and machine learning, and portfolio-grade apps.
Ideas alone are cheap, so each theme also ends with a runnable starter project using only the standard library. I explain it line by line, and you can run it right here in the browser, change it, and grow it into the first idea in that section. Pick one theme, build the starter, tick off a checklist, and then publish the result; the companion lesson on portfolio and GitHub shows you how.
What you will learn
- βChoose a project whose size matches your current skill
- βTurn a vague idea into a goal, a checklist and a stretch goal
- βBuild command-line tools that parse arguments and print clean output
- βProcess text and files with
re,Counterandpathlib - βDesign data-handling code such as expense splitting with correct money maths
- βModel games as functions and state so that they can be tested without a window
- βStructure a larger program with classes, errors and small tests
- βPlan stretch goals so that one project can grow for weeks
Why programmers should learn this
- β Projects force you to combine skills, which is exactly what exercises and quizzes avoid; you learn how to decide where a function ends and a module begins.
- β Finishing something small and complete teaches more than half-building something big, because the last twenty percent (errors, edge cases, README) is where real habits form.
- β A feature checklist turns a fuzzy wish into testable steps, which is the same planning skill used in professional software work.
- β Working on things you find interesting keeps you practising on days when motivation is low; a game, a budget tool or a file organiser is easier to return to than a drill.
- β A handful of finished, explained projects gives you something concrete to talk about and to show, without any promises about outcomes: the work speaks for itself.
How to pick and scope a project
The most common reason projects die is size, not difficulty. An idea such as "a social network" has hundreds of parts, and you will quit after the first week. A good project has one clear sentence describing what it does, and you can finish a first version in a few evenings. If you cannot describe it in one sentence, shrink it until you can.
I use a simple recipe. Write the goal in one sentence. List the skills it will exercise, and check that at most one or two are new to you; a project made only of new things is frustrating, and one made only of old things teaches nothing. Write a feature checklist of three to six items that you can tick off, ordered so that the program is usable after the first item. Finally add a stretch goal, an optional next step, so you always know what to do if you finish early.
Build in thin slices. Get the smallest end-to-end version running first, even if it is ugly: it takes input, does one thing, prints a result. Then add one checklist item at a time and run the program after each. This is far less risky than writing a thousand lines and discovering on the first run that nothing works. Commit to version control after every working slice; the portfolio lesson explains the habit.
Finally, be honest about level. The themes below are ordered roughly from gentler to more demanding, but inside each theme the ideas also rise in difficulty. If a checklist item looks impossible, skip it and come back later; if you finish it in an hour, jump to the stretch goal. Nobody needs to build all fifty; two or three finished projects beat fifty abandoned folders.
project = {
"goal": "Count the most common words in a text file.",
"skills": ["re", "Counter", "sorting"],
"checklist": [
("Read a file and lower-case it", True),
("Ignore punctuation", True),
("Ignore common words", False),
("Show the top N words", False),
],
"stretch": "Compare two files.",
}
done = sum(1 for _, ok in project["checklist"] if ok)
total = len(project["checklist"])
print("Goal:", project["goal"])
print("Skills:", ", ".join(project["skills"]))
for item, ok in project["checklist"]:
print(f" [{'x' if ok else ' '}] {item}")
print(f"Progress: {done}/{total}")
print("Stretch:", project["stretch"])Goal: Count the most common words in a text file. Skills: re, Counter, sorting [x] Read a file and lower-case it [x] Ignore punctuation [ ] Ignore common words [ ] Show the top N words Progress: 2/4 Stretch: Compare two files.
Line by line
- 1-11A project plan is just data: a goal, the skills, a checklist of (item, finished?) pairs and a stretch goal.
- 13-14Count finished items with a generator expression, and the total with
len. - 15-16Print the goal and join the skill names into one line.
- 17-18Print each checklist item with an
xbox when it is finished. - 19-20Show progress and the stretch goal, the thing to build next.
Write the checklist before the first line of code and keep it in a README.md at the top of the project. Ticking items off is motivating, and the file becomes the start of your documentation.
Theme 1: command-line tools, with a starter
Command-line programs are the friendliest place to start. There is no window or web page to build, input is a few arguments, and output is text, so you can focus on logic. They also teach you argparse, exit codes and reading from files, which every later theme reuses. Here are seven ideas.
To-do list manager. Goal: a program where you add, list and complete tasks from the terminal. Skills practised: argparse sub-commands, lists of dictionaries, JSON for saving. Feature checklist: add, list, done and delete commands; numbered tasks; tasks saved between runs; friendly message for unknown numbers. Stretch goal: due dates and a --overdue filter
Unit converter. Goal: convert lengths, weights and temperatures from the command line. Skills practised: dictionaries of factors, argument validation, functions. Feature checklist: convert 5 km mi style syntax; at least three categories; error for incompatible units; two decimal places. Stretch goal: accept a whole expression such as 10 kg to lb
Tip and bill calculator. Goal: work out the tip and per-person amount for a restaurant bill. Skills practised: float versus Decimal, rounding, input validation. Feature checklist: bill, tip percentage and head-count options; sensible defaults; reject negative numbers; show a small summary table. Stretch goal: round up to the nearest coin and show who pays the extra cent
Countdown and stopwatch. Goal: print how many days remain until a date, or time a task. Skills practised: datetime, argparse, formatting durations. Feature checklist: parse a date argument; show days, hours and minutes; handle dates in the past; a --label option. Stretch goal: store several named countdowns in a file
Quick notes tool. Goal: append timestamped notes to a text file and search them later. Skills practised: file append mode, pathlib, string search. Feature checklist: note add, note list, note search word; one note per line; creates the file on first use. Stretch goal: tags such as #idea and a --tag filter
Directory size reporter. Goal: show the biggest files and folders under a given path. Skills practised: pathlib, recursion, sorting by a key, human-readable sizes. Feature checklist: walk a folder; sum sizes per sub-folder; show the top ten; convert bytes to KB, MB and GB; skip unreadable files. Stretch goal: a simple text bar chart for each entry
Random picker and dice roller. Goal: pick a winner from a list, or roll dice written as 2d6+3. Skills practised: random, regular expressions, parsing a mini-language. Feature checklist: parse the dice notation; allow a seed for repeatable results; print each roll and the total; reject bad notation. Stretch goal: advantage and disadvantage rolls
The common thread in these seven ideas is that the interesting code lives in ordinary functions that take values and return values, while a thin layer at the edge reads the command line and prints. Keep that separation and you will be able to test the logic without typing commands, which is what the starter below does.
Here is the first runnable starter. It is the skeleton of the to-do idea: sub-commands built with argparse, a list of dictionaries as the data store, and a run function that takes the argument list as a parameter. Real programs read sys.argv automatically, but passing the list explicitly lets us call the program several times in one script, which is how I test command-line tools.
Notice that run returns a string rather than printing. Returning text keeps the function easy to test; the caller decides whether to print it. When you add saving to a JSON file later, only the code that loads and stores tasks has to change.
import argparse
def build_parser():
parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add a task")
add.add_argument("text")
done = sub.add_parser("done", help="complete a task")
done.add_argument("number", type=int)
sub.add_parser("list", help="show tasks")
return parser
def run(argv, tasks):
args = build_parser().parse_args(argv)
if args.command == "add":
tasks.append({"text": args.text, "done": False})
return f"Added: {args.text}"
if args.command == "done":
if not 1 <= args.number <= len(tasks):
return f"No task number {args.number}"
tasks[args.number - 1]["done"] = True
return f"Completed: {tasks[args.number - 1]['text']}"
lines = []
for position, task in enumerate(tasks, start=1):
mark = "x" if task["done"] else " "
lines.append(f"{position}. [{mark}] {task['text']}")
return "\n".join(lines) or "Nothing to do"
tasks = []
script = (["add", "Buy rice"], ["add", "Write README"],
["done", "1"], ["list"], ["done", "9"])
for argv in script:
print(run(argv, tasks))Added: Buy rice Added: Write README Completed: Buy rice 1. [x] Buy rice 2. [ ] Write README No task number 9
Line by line
- 1
argparseturns the words typed after the program name into structured values. - 3-10
build_parserdeclares three sub-commands.addtakes some text,donetakes a number converted withtype=int, andlisttakes nothing.required=Truemakes a missing command an error. - 12-13
runreceives the argument list and the task list, and parses the arguments. - 14-16For
addwe append a dictionary and return a confirmation message. - 17-21For
donewe first check the number is in range, using a chained comparison, then flip the flag. The task number is one-based for people, so we subtract one for the list index. - 22-26Anything else is
list: loop withenumerate(..., start=1), build one line per task, and join them. Theorsupplies a message when the result is empty. - 28-32Instead of typing commands, a scripted list of argument lists plays the part of the user. Each run prints its result.
To grow this into the full idea, add a delete command, then load and save tasks with the json module at the start and end of the program. Handle the case where the file does not exist yet.
Theme 2: text and files, with a starter
Text is the most common data you will meet. Logs, essays, subtitles, notes, configuration: all of it is strings in files. Projects in this theme teach you the three tools I use constantly: string methods for simple jobs, regular expressions for patterns, and pathlib for locating and reading files without fighting path separators. Most are quick to build and satisfying to run on your own documents.
Word-frequency counter. Goal: count the most common words in a text file. Skills practised: re.findall, Counter, sorting with a key, stop-word sets. Feature checklist: lower-case the text; ignore punctuation; ignore common words; show the top N with counts; accept a file path. Stretch goal: plot the counts or compare two files
Log file analyser. Goal: summarise a server or application log. Skills practised: regular expressions with groups, dictionaries, datetime parsing. Feature checklist: count lines by level; list the most frequent error messages; find the busiest minute; skip malformed lines without crashing. Stretch goal: write a short report to a Markdown file
Bulk file renamer. Goal: rename a folder of files by a rule such as 001_name.jpg. Skills practised: pathlib, string formatting, dry-run mode. Feature checklist: preview changes first with --dry-run; zero-pad numbers; never overwrite an existing file; undo list saved to a file. Stretch goal: a regular-expression rename mode
Markdown to HTML converter. Goal: convert headings, bold text and lists into HTML. Skills practised: re.sub, line-by-line processing, escaping. Feature checklist: headings with #; paragraphs; bold and italic; bullet lists; escape < and & first. Stretch goal: fenced code blocks and links
Duplicate file finder. Goal: find files with identical content in a folder tree. Skills practised: hashlib, grouping with dictionaries, pathlib.rglob. Feature checklist: hash file contents in chunks; group by hash; print each group; skip empty files; never delete automatically. Stretch goal: compare by size first for speed
Flashcard quizzer. Goal: quiz yourself from a CSV file of questions and answers. Skills practised: csv, random, scoring, file reading. Feature checklist: load cards; shuffle; ask and compare ignoring case; show score; save the cards you missed. Stretch goal: spaced repetition: cards you miss come back sooner
Whenever a project reads a file, separate reading from processing. A function that takes a string and returns counts is trivial to test; a function that opens a file and also counts is not. The starter below follows that rule.
This starter keeps the counting function pure: it takes text and returns a Counter. The file handling is a thin wrapper around it. We use a temporary folder so the example is safe to run anywhere, including in your browser, but in your own project you would pass a real path.
The regular expression [a-z']+ matches runs of lower-case letters and apostrophes, so "don't" stays one word and punctuation disappears. We lower-case the text first so that "The" and "the" count together. Sorting by (-count, word) gives a stable order: highest count first, ties alphabetical, which also makes the output reproducible.
import re
import tempfile
from collections import Counter
from pathlib import Path
STOP_WORDS = {"the", "a", "and", "of", "to", "is", "in", "it"}
def word_counts(text):
words = re.findall(r"[a-z']+", text.lower())
return Counter(w for w in words if w not in STOP_WORDS)
sample = ("The cat and the dog. The dog chased the cat; "
"the cat ran to the tree. A dog is a dog.")
with tempfile.TemporaryDirectory() as folder:
path = Path(folder) / "sample.txt"
path.write_text(sample, encoding="utf-8")
counts = word_counts(path.read_text(encoding="utf-8"))
ranked = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
for word, number in ranked[:5]:
print(f"{word:<8}{number}")dog 4 cat 3 chased 1 ran 1 tree 1
Line by line
- 1-4Import regular expressions, a temporary folder helper,
Counterfor tallying andPathfor file paths. - 6Stop words are very common words we do not want to dominate the ranking. A set makes lookups fast.
- 8-10
word_countslower-cases the text, extracts words with a regular expression and counts those that are not stop words. - 12-13A sample text split over two lines inside parentheses.
- 15-18Write the sample into a file inside a temporary directory, read it back and count. The folder disappears when the
withblock ends. - 20-22Sort by descending count, then alphabetically, and print the top five with aligned columns using the
:<8format spec.
Extend it by accepting a file path with argparse, adding a --top option, and loading stop words from a file the user can edit.
Theme 3: web and APIs, with a starter
Web projects connect your code to the rest of the internet. For a beginner the important lesson is that web work is mostly data in, data out: you receive a request or a response, usually JSON, validate it, transform it and send something back. The ideas here use public APIs and small web frameworks. Library APIs and rate limits change, so check each service's current documentation and terms before you build, and never put secret keys in code you publish.
Weather dashboard in the terminal. Goal: show the forecast for a city. Skills practised: HTTP requests, JSON, error handling, timeouts. Feature checklist: city from arguments; clear message when the network fails; temperature units option; a cache file to avoid repeated requests. Stretch goal: a multi-city summary table
URL shortener. Goal: create short codes for long links. Skills practised: a web framework route, dictionaries or SQLite, validation. Feature checklist: create a code; redirect from the code; reject invalid URLs; do not repeat codes; count visits. Stretch goal: expiry dates and a stats page
Link checker. Goal: find broken links on a web page. Skills practised: HTML parsing, status codes, sets, timeouts. Feature checklist: fetch a page; collect links; check each once; report status codes; skip mailto and anchors. Stretch goal: check pages in parallel with a limit
Currency or crypto price tracker. Goal: look up prices and keep a history. Skills practised: API calls, CSV or SQLite storage, scheduling. Feature checklist: fetch a price; store it with a timestamp; show min, max and average; handle API errors without losing data. Stretch goal: a chart of the stored history
Personal REST API. Goal: expose a small collection, such as books you have read. Skills practised: routes, JSON, status codes, validation, tests. Feature checklist: list, create, update and delete; return 404 for unknown ids; validate fields; automated tests for each route. Stretch goal: pagination and filtering
Password-strength checker service. Goal: score passwords on the server side. Skills practised: regular expressions, scoring rules, input validation. Feature checklist: length rule; character classes; a common-password list; helpful suggestions; never log or store the password. Stretch goal: a breached-password check using a safe k-anonymity service
To make web code testable without a network, keep the business rules in plain functions and call the network from a small wrapper you can replace with a fake. The starter I chose for this theme is the core of the last idea, because input validation is the part of every web application that must be right.
Every sign-up form needs a function like this, and it is a nice exercise in turning rules into a score. The function returns three things: a numeric score, a label and a list of suggestions, so the caller can show friendly feedback. It does not print or store the password, which is a rule I would keep in every real version.
I use a table of (pattern, label) pairs to check each character class in a loop. This keeps the function short and makes it easy to add a rule: add one more row. The common-password check comes first because a long but famous password is still weak. Remember that modern guidance cares more about length and avoiding known-bad passwords than about forcing odd symbols, so treat this score as a teaching exercise, not a security product.
import re
COMMON = {"password", "123456", "qwerty", "letmein", "welcome"}
CLASSES = (
(r"[a-z]", "a lowercase letter"),
(r"[A-Z]", "an uppercase letter"),
(r"\d", "a digit"),
(r"[^A-Za-z0-9]", "a symbol"),
)
def check_password(pw):
if pw.lower() in COMMON:
return 0, "Weak", ["this is a very common password"]
score, notes = 0, []
if len(pw) >= 12:
score += 2
elif len(pw) >= 8:
score += 1
else:
notes.append("use at least 8 characters")
for pattern, label in CLASSES:
if re.search(pattern, pw):
score += 1
else:
notes.append(f"add {label}")
if re.search(r"(.)\1\1", pw):
score -= 1
notes.append("avoid repeating one character three times")
score = max(score, 0)
label = "Weak" if score <= 2 else "Okay" if score <= 4 else "Strong"
return score, label, notes
for candidate in ("password", "abc", "Summer2024", "correct-Horse-battery-9"):
score, label, notes = check_password(candidate)
print(f"{candidate!r}: {score} {label}")
for note in notes:
print(" -", note)'password': 0 Weak - this is a very common password 'abc': 1 Weak - use at least 8 characters - add an uppercase letter - add a digit - add a symbol 'Summer2024': 4 Okay - add a symbol 'correct-Horse-battery-9': 6 Strong
Line by line
- 1
reis used to test which kinds of character appear. - 3A small set of well-known bad passwords; a real checker would load a much larger list.
- 4-9Each rule is a pattern and the phrase to use when it is missing.
- 11-13Famous passwords are rejected immediately with a score of zero.
- 14-20Length earns up to two points; a short password adds a suggestion.
- 21-25Loop through the character classes: a match adds a point, a miss adds a suggestion.
- 26-28
(.)\1\1matches any character followed by itself twice, soaaais penalised. - 29-31Clamp the score at zero and turn it into a label with chained conditional expressions.
- 33-37Try four candidates and print the score, label and suggestions.
For the stretch goal, load common passwords from a file and compare in lower case. Do not send real passwords to any service you do not control.
Theme 4: data, with a starter
Data projects teach you to ask questions of numbers: how much, how often, which is biggest. Most start with a CSV file or a list of records and end with a summary. They are also where correct money handling matters, because floating-point numbers cannot represent most decimal fractions exactly. A habit worth building now is to store money as whole cents (integers) or as Decimal, and only format it for display at the end.
Expense splitter. Goal: share a group's costs fairly and say who pays whom. Skills practised: dictionaries, integer maths with divmod, greedy algorithms. Feature checklist: record who paid what; compute each person's fair share; list the minimum sensible transfers; handle uneven cents. Stretch goal: weighted shares, for example a person who stayed fewer nights
Personal budget tracker. Goal: record income and spending by category and show monthly totals. Skills practised: CSV, defaultdict, dates, formatting tables. Feature checklist: add an entry; totals per category and month; warn when a category passes its limit; save and reload. Stretch goal: a bar chart per category
Grade book. Goal: store marks and compute averages and letter grades. Skills practised: lists of dictionaries, statistics, sorting. Feature checklist: add students and scores; mean, median and highest; grade boundaries in a dictionary; handle missing scores. Stretch goal: export a report card as text
CSV cleaner. Goal: fix messy spreadsheet exports. Skills practised: csv, string cleaning, validation, error reports. Feature checklist: trim spaces; normalise case; parse dates in several formats; flag rows that cannot be fixed instead of dropping them silently. Stretch goal: a rules file that says how each column is cleaned
Habit tracker. Goal: record daily habits and show streaks. Skills practised: dates, sets, longest-run logic, persistence. Feature checklist: tick a habit for today; current and longest streak; weekly summary; data survives restarts. Stretch goal: a text calendar heat-map
Mini SQL notebook. Goal: store records in sqlite3 and answer questions with queries. Skills practised: SQL basics, parameters, the sqlite3 module. Feature checklist: create a table; insert rows safely with placeholders; five useful queries; print results as a table. Stretch goal: an import command that loads a CSV file
Whatever the domain, a good data project separates the records, the calculation and the presentation. The starter below does exactly that for the expense splitter: it works with integer cents, produces a list of transfers, and only formats money at the print step.
Here is the idea in numbers. If three friends pay 90, 30 and 0 for a trip, the total is 120 and each fair share is 40. The first friend is owed 50, the second owes 10, the third owes 40. The code computes those balances, then repeatedly matches the biggest debtor with the biggest creditor, which keeps the number of transfers small. It is a greedy method, not always the absolute minimum, but it is easy to understand and good enough for friends.
Look closely at divmod. When the total does not divide evenly, such as 100 cents between three people, someone has to pay the extra cent. We give one extra cent to the first few people in alphabetical order, so the shares always add up to exactly the total. Losing or inventing a cent is the classic bug in money code.
def split_expenses(paid):
people = sorted(paid)
total = sum(paid.values())
share, extra = divmod(total, len(people))
owed = {p: share + (1 if i < extra else 0) for i, p in enumerate(people)}
balance = {p: paid[p] - owed[p] for p in people}
creditors = [[b, p] for p, b in sorted(balance.items()) if b > 0]
debtors = [[-b, p] for p, b in sorted(balance.items()) if b < 0]
creditors.sort(key=lambda x: (-x[0], x[1]))
debtors.sort(key=lambda x: (-x[0], x[1]))
transfers = []
i = j = 0
while i < len(debtors) and j < len(creditors):
amount = min(debtors[i][0], creditors[j][0])
transfers.append((debtors[i][1], creditors[j][1], amount))
debtors[i][0] -= amount
creditors[j][0] -= amount
if debtors[i][0] == 0:
i += 1
if creditors[j][0] == 0:
j += 1
return transfers
def money(cents):
return f"{cents / 100:.2f}"
trip = {"Ana": 9000, "Ben": 3000, "Cy": 0}
for debtor, creditor, cents in split_expenses(trip):
print(f"{debtor} pays {creditor} {money(cents)}")
odd = {"Dee": 10000, "Eli": 0, "Fay": 0}
transfers = split_expenses(odd)
print(transfers)
print("moved:", money(sum(c for _, _, c in transfers)))Cy pays Ana 40.00
Ben pays Ana 10.00
[('Eli', 'Dee', 3333), ('Fay', 'Dee', 3333)]
moved: 66.66Line by line
- 1-4Amounts arrive as integer cents.
divmodgives each person's base share and the number of leftover cents. - 5The first
extrapeople in alphabetical order pay one cent more, so the shares add up to the total exactly. - 6A positive balance means a person paid more than their share and is owed money; a negative one means they owe.
- 8-11Build lists of creditors and debtors as
[amount, name], biggest first, with the name as a tie-breaker so results are reproducible. - 13-23Walk both lists with two pointers. Each transfer is the smaller of what the debtor owes and the creditor is owed. Reduce both, and move on whichever reaches zero.
- 26-27
moneyformats cents for display only, at the very end. - 29-31Ana paid 90, Ben 30, Cy nothing; each share is 40, so Cy owes 40 and Ben owes 10.
- 33-36A second case with an uneven split: 100.00 between three people gives shares of 33.34, 33.33 and 33.33, and the transfers add up exactly.
Extend it by reading expenses from a CSV with one row per payment (who, amount, note), by splitting each payment among only the people involved, and by rejecting negative amounts.
Theme 5: automation, with a starter
Automation is Python at its most immediately useful: the program does a boring job so you do not have to. The best automation projects solve a problem you actually have, such as messy folders, repeated copy-and-paste, or checking something every day. Two rules apply to all of them. First, build a dry-run mode that shows what would happen without changing anything. Second, never delete or overwrite without an explicit instruction, because a script runs faster than you can react.
Downloads folder organiser. Goal: sort files into folders by type. Skills practised: pathlib, dictionaries of extensions, dry-run mode. Feature checklist: map extensions to folders; preview first; skip sub-folders; avoid overwriting by adding a number; print a summary. Stretch goal: an undo command that reads a log of moves
Daily report generator. Goal: gather facts and write a short text or HTML report. Skills practised: string templates, datetime, file writing. Feature checklist: collect three facts; fill a template; save with the date in the file name; never overwrite yesterday's report. Stretch goal: email it with the techniques in the email automation lesson
Spreadsheet merger. Goal: combine several CSV files into one. Skills practised: csv, headers, consistent columns, error handling. Feature checklist: check that headers match; add a source column; skip empty files; report rows that did not fit. Stretch goal: detect and remove duplicate rows
Backup script. Goal: copy changed files from one folder to another. Skills practised: shutil, file times, hashing, logging. Feature checklist: copy only new or changed files; keep the folder structure; log every action; dry-run mode. Stretch goal: keep the last N dated versions
Reminder and timer bot. Goal: run a task at set times from a schedule file. Skills practised: datetime, loops with sleep, parsing a schedule. Feature checklist: read times from a file; trigger a message at each; handle times already passed; stop with a key press. Stretch goal: repeat rules such as every weekday
Form filler for plain-text templates. Goal: generate many letters or certificates from one template and a CSV. Skills practised: string.Template, CSV, file output. Feature checklist: one output per row; clean file names; report missing fields; a preview of the first result. Stretch goal: export to PDF with a library of your choice
The starter below is a small organiser. It builds its own temporary folder with a few files, shows a dry run, and then performs the moves. Pay attention to how the plan is returned as data, so the same function serves both the preview and the real run.
import tempfile
from pathlib import Path
FOLDERS = {".jpg": "images", ".png": "images", ".pdf": "documents",
".txt": "documents", ".csv": "data"}
def organise(folder, dry_run=True):
plan = []
for item in sorted(folder.iterdir()):
if not item.is_file():
continue
target = FOLDERS.get(item.suffix.lower(), "other")
plan.append((item.name, target))
if not dry_run:
destination = folder / target
destination.mkdir(exist_ok=True)
item.rename(destination / item.name)
return plan
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
for name in ("trip.JPG", "cv.pdf", "notes.txt", "sales.csv", "mystery.bin"):
(folder / name).write_text("demo", encoding="utf-8")
print("Dry run:")
for name, target in organise(folder):
print(f" {name} -> {target}/")
organise(folder, dry_run=False)
print("After the real run:")
for path in sorted(folder.rglob("*")):
if path.is_file():
print(" ", path.relative_to(folder).as_posix())Dry run: cv.pdf -> documents/ mystery.bin -> other/ notes.txt -> documents/ sales.csv -> data/ trip.JPG -> images/ After the real run: data/sales.csv documents/cv.pdf documents/notes.txt images/trip.JPG other/mystery.bin
Line by line
- 1-2
tempfilegives us a safe scratch folder andPathhandles file paths. - 4-5A dictionary maps lower-case extensions to folder names.
- 7-9
organisereturns a plan, a list of(file, folder)pairs. We sort the directory listing so the order is predictable. - 10-12Skip anything that is not a plain file, such as sub-folders. Use
.suffix.lower()so.JPGmatches too; unknown types go toother. - 13-17Only when
dry_runis false do we create the folder and move the file withrename. - 20-23Create the demo files inside a temporary directory.
- 25-28The dry run prints what would happen and changes nothing.
- 30-34Run for real, then list every file with its path relative to the folder.
Add collision handling next: if the destination already has a file with that name, add a number to the new name rather than overwriting.
Theme 6: games, with two starters
Games are wonderful for learning because the rules are clear and the feedback is immediate. You do not need a graphics library to start. A game is a state (the board, the score, the room you are in), a set of rules that change the state, and a loop that asks for the next move. If you model those three things in plain functions, you can test the game with scripted moves and add a window later. Windowed libraries such as pygame come after this; see the pygame lesson when you are ready.
Number guessing game. Goal: guess a secret number with higher or lower hints. Skills practised: random, loops, comparison, counting attempts. Feature checklist: pick a secret in a range; hints; count guesses; limit attempts; play again. Stretch goal: a bot that guesses using binary search
Rock, paper, scissors. Goal: play against the computer over several rounds. Skills practised: dictionaries for rules, random.choice, scoring. Feature checklist: three choices; clear win rules; best-of-N; show running score; reject bad input. Stretch goal: a computer that learns your habits
Hangman. Goal: guess letters of a hidden word. Skills practised: sets, strings, loops, word lists. Feature checklist: hidden word shown as underscores; wrong guesses counted; repeated guesses ignored; win and lose messages. Stretch goal: categories and a difficulty level
Text adventure. Goal: explore rooms, pick up items and reach a goal. Skills practised: dictionaries as maps, state, commands, loops. Feature checklist: at least five rooms; go, take and look commands; an inventory; a win condition. Stretch goal: save and load the game
Tic-tac-toe. Goal: two players, or a player against the computer. Skills practised: lists, win checking, functions, recursion for the stretch. Feature checklist: draw the board; alternate turns; reject taken squares; detect a win and a draw. Stretch goal: an unbeatable computer using minimax
Dice game such as Yahtzee-lite. Goal: score combinations of five dice. Skills practised: collections.Counter, scoring functions, seeds. Feature checklist: roll five dice; hold some and re-roll; score pairs, triples and runs; seeded rolls for tests. Stretch goal: a full scorecard with totals and bonuses
Memory match in text. Goal: match pairs of hidden cards. Skills practised: 2D lists, shuffling, state. Feature checklist: a grid of hidden pairs; reveal two; keep or hide them; count turns; detect completion. Stretch goal: a timer and a best-score file
Two starters follow. The first is a number guessing game where a bot does the guessing, using a seeded random generator so the secret is the same every time. The second is a scripted text adventure: the player's commands come from a list, which is exactly how you would write an automated test for it.
import random
def play(low, high, seed):
secret = random.Random(seed).randint(low, high)
turns = 0
while True:
guess = (low + high) // 2
turns += 1
if guess == secret:
return f"Found {secret} in {turns} guesses"
if guess < secret:
print(f" {guess}: too low")
low = guess + 1
else:
print(f" {guess}: too high")
high = guess - 1
print(play(1, 100, seed=7))
print(play(1, 100, seed=8))50: too high 25: too low 37: too low 43: too high 40: too low 41: too low Found 42 in 7 guesses 50: too high 25: too low 37: too high 31: too high 28: too low 29: too low Found 30 in 7 guesses
Line by line
- 1The
randommodule provides pseudo-random numbers. - 3-4
random.Random(seed)creates a private generator; the same seed always gives the same secret, so the game is repeatable. - 5-8Each turn the bot guesses the middle of the remaining range and counts the turn.
- 9-10A correct guess ends the game with a summary string.
- 11-16Otherwise it prints the hint and shrinks the range to the half that can still contain the secret.
- 18-19Two different seeds give two different games. For a human player you would remove the seed and replace the bot with
input().
ROOMS = {
"hall": {"text": "A dusty hall. A door leads north.", "exits": {"north": "library"}, "items": []},
"library": {"text": "Shelves of old books. A key lies here.", "exits": {"south": "hall", "east": "vault"}, "items": ["key"]},
"vault": {"text": "The vault. You made it!", "exits": {"west": "library"}, "items": []},
}
def play(commands):
room, bag = "hall", []
print(ROOMS[room]["text"])
for command in commands:
verb, _, noun = command.partition(" ")
here = ROOMS[room]
if verb == "go" and noun in here["exits"]:
target = here["exits"][noun]
if target == "vault" and "key" not in bag:
print("The vault door is locked.")
continue
room = target
print(ROOMS[room]["text"])
elif verb == "take" and noun in here["items"]:
here["items"].remove(noun)
bag.append(noun)
print(f"You take the {noun}.")
else:
print("You can't do that.")
if room == "vault":
print("You win!")
break
play(["go east", "go north", "go east", "take key", "dance", "go east"])A dusty hall. A door leads north. You can't do that. Shelves of old books. A key lies here. The vault door is locked. You take the key. You can't do that. The vault. You made it! You win!
Line by line
- 1-5The whole world is a dictionary: each room has a description, a map of exits and a list of items.
- 7-9
playtracks two pieces of state, the current room and the bag, and describes the starting room. - 10-11
partitionsplits a command such asgo northinto a verb and a noun at the first space. - 13-19Moving requires a valid exit; the vault is locked unless the key is in the bag.
continueskips the rest of that turn. - 20-23Taking an item moves it from the room's list into the bag.
- 24-25Anything unrecognised produces a polite refusal instead of crashing.
- 26-28Reaching the vault wins and stops the loop.
- 30The command list stands in for a player. Notice that the first
go eastfails because there is no such exit.
Both starters have no input at all, so they run anywhere and are trivial to test. When you are happy with the logic, wrap it in a loop that calls input() on your own computer.
Theme 7: AI and machine learning, with a starter
Machine learning projects are easier than they look if you start with small data and simple models. The key lesson is that most of the work is not the model: it is preparing the data, splitting it into training and test sets, and measuring honestly. A project that reports its accuracy on the same data it trained on teaches the wrong thing, so every idea below includes an evaluation step. Some ideas need libraries such as NumPy, pandas and scikit-learn, which run in the browser here; larger tools such as PyTorch are best on your own machine. See the scikit-learn and NumPy lessons for the basics.
Game AI for tic-tac-toe. Goal: a computer opponent that never loses. Skills practised: recursion, minimax, game state as data. Feature checklist: detect wins; list legal moves; score positions recursively; choose the best move; test on known positions. Stretch goal: alpha-beta pruning for speed
House or used-item price predictor. Goal: predict a number from a few features. Skills practised: pandas, train-test split, linear regression, error metrics. Feature checklist: load a small data set; split it; train; report average error; compare with simply guessing the average. Stretch goal: try a second model and compare
Spam or sentiment classifier. Goal: label short texts as one of two classes. Skills practised: text cleaning, bag-of-words, scikit-learn, confusion matrix. Feature checklist: prepare labelled data; vectorise; train; show precision and recall; test on new sentences. Stretch goal: examine the words the model finds most useful
Clustering explorer. Goal: group similar items without labels. Skills practised: k-means, scaling, plotting. Feature checklist: scale features; try several values of k; plot groups; describe each group in words. Stretch goal: a way to choose k, such as the elbow method
Recommendation by similarity. Goal: suggest items similar to one you like. Skills practised: vectors, cosine similarity, dictionaries. Feature checklist: represent items as vectors; compute similarity; rank; exclude the item itself; explain why each was suggested. Stretch goal: combine two kinds of features
Chatbot with rules, then with an API. Goal: answer common questions. Skills practised: string matching, intents, then an API call. Feature checklist: five intents with keywords; a fallback reply; logging unanswered questions; a test file of expected replies. Stretch goal: swap the rules for a language-model API using the techniques in the LLM APIs lesson, keeping the test file
The starter is the first idea. The computer plays O using minimax: it looks at every possible continuation, assumes both sides play perfectly, and picks the move with the best guaranteed result. The human side is played by a scripted list of moves so the game runs in the browser without input(). Tic-tac-toe is small enough that checking every continuation takes well under a second.
LINES = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6),
(1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
def winner(board):
for a, b, c in LINES:
if board[a] != " " and board[a] == board[b] == board[c]:
return board[a]
return None
def minimax(board, player):
won = winner(board)
if won:
return (1 if won == "O" else -1), None
moves = [i for i, cell in enumerate(board) if cell == " "]
if not moves:
return 0, None
best_score, best_move = (-2 if player == "O" else 2), None
for move in moves:
board[move] = player
score, _ = minimax(board, "X" if player == "O" else "O")
board[move] = " "
if (player == "O" and score > best_score) or (player == "X" and score < best_score):
best_score, best_move = score, move
return best_score, best_move
def show(board):
for r in range(0, 9, 3):
print("|".join(board[r:r + 3]))
print()
board = [" "] * 9
for x_move in [0, 8, 5, 1, 7]:
if board[x_move] != " " or winner(board):
break
board[x_move] = "X"
if winner(board) or " " not in board:
break
_, o_move = minimax(board, "O")
board[o_move] = "O"
show(board)
print("Winner:", winner(board) or "nobody yet")X|O|O |O|X | |X Winner: nobody yet
Line by line
- 1-2The eight winning lines of the board, as index triples for a nine-item list.
- 4-8
winnerreturnsXorOif three equal non-blank cells line up, otherwiseNone. - 10-13Base case: a won position scores +1 if O won and -1 if X won, so O is the maximiser.
- 14-16With no empty squares left the game is a draw and scores 0.
- 17Start from the worst possible score for whoever is choosing.
- 18-24Try each legal move: place it, recurse for the other player, undo it, and keep the best result for the current player. O keeps the highest score, X the lowest.
- 26-29
showprints the board as three rows. - 32-40The scripted X moves stand in for a human. After each, we stop if the game is over; otherwise O asks minimax for its best reply.
- 41-42Print the final board and the result. Because O plays perfectly, X cannot win.
Stretch it by letting O move first, then add a counter of how many positions were examined, and finally add alpha-beta pruning and watch the counter drop.
Theme 8: portfolio-grade apps, with a starter
The last theme is for when you can already build the others. A portfolio-grade project is not necessarily bigger; it is more complete. It has a clear README, a sensible structure, error handling, tests and a short note about the decisions you made. These are the qualities that make someone reading your code believe you can maintain it. I make no promises about what any employer will think, but a finished, explained project is always a better learning record than a half-finished one.
Bank account simulation. Goal: model accounts, deposits, withdrawals and statements. Skills practised: classes, custom exceptions, money in cents, tests. Feature checklist: deposit and withdraw with validation; overdraft error; transaction history; transfer between accounts; tests for every rule. Stretch goal: interest applied monthly and a statement printer
Library or inventory manager. Goal: track items, borrowers and due dates. Skills practised: classes, dataclasses, SQLite or JSON storage, dates. Feature checklist: add and remove items; lend and return; list overdue items; persistent storage; unit tests. Stretch goal: a small web or desktop front end
Quiz engine with question packs. Goal: load question files and run quizzes. Skills practised: JSON, classes, randomness with seeds, scoring. Feature checklist: several question types; load packs from files; score and review; validate pack files; tests. Stretch goal: statistics on which questions are missed most
Personal finance dashboard. Goal: combine budgets, charts and reports. Skills practised: pandas, matplotlib, CSV import, report generation. Feature checklist: import transactions; categorise; monthly charts; a summary page; tests for the categoriser. Stretch goal: rules the user can edit
Small web application with a database. Goal: a notes, recipes or book-tracking site. Skills practised: a web framework, SQL, forms, validation, deployment. Feature checklist: create, read, update and delete; input validation; error pages; a README with setup steps; tests. Stretch goal: user accounts, handled carefully with a trusted library
A command-line tool published as a package. Goal: something you would genuinely install. Skills practised: packaging, entry points, versioning, documentation. Feature checklist: a working pyproject.toml; a command with --help; tests; a changelog; installable in a clean environment. Stretch goal: publish it to a test index to learn the process
The starter is the bank account idea in miniature. It shows the three habits that make a project feel complete: a custom exception for a business rule, integer cents for money, and a few tests written with plain assert. In a real project you would move the tests to a separate file and run them with pytest, as the pytest lesson explains.
class InsufficientFunds(Exception):
pass
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = []
def deposit(self, cents):
if cents <= 0:
raise ValueError("deposit must be positive")
self.balance += cents
self.history.append(("deposit", cents))
def withdraw(self, cents):
if cents <= 0:
raise ValueError("withdrawal must be positive")
if cents > self.balance:
raise InsufficientFunds(f"{self.owner} has only {self.balance / 100:.2f}")
self.balance -= cents
self.history.append(("withdraw", cents))
def transfer(source, target, cents):
source.withdraw(cents)
target.deposit(cents)
# Tests written with plain assert
a, b = Account("Ana", 5000), Account("Ben")
transfer(a, b, 1500)
assert (a.balance, b.balance) == (3500, 1500)
assert b.history == [("deposit", 1500)]
try:
a.withdraw(99999)
except InsufficientFunds as error:
print("Refused:", error)
else:
raise AssertionError("overdraft should have failed")
try:
a.deposit(-5)
except ValueError as error:
print("Refused:", error)
print("All checks passed")Refused: Ana has only 35.00 Refused: deposit must be positive All checks passed
Line by line
- 1-2A custom exception names a business rule: you cannot spend money you do not have.
- 4-8An account stores its owner, balance in cents and a history list.
- 10-14
depositvalidates the amount, changes the balance and records the transaction. - 16-22
withdrawrejects non-positive amounts and overdrafts, and only changes anything after both checks pass. - 24-26
transferis a function of two accounts. Becausewithdrawcan raise, the deposit never happens if the withdrawal fails. - 29-32Plain
assertstatements check the balances and the history after a transfer. - 34-39Check that an overdraft raises the right exception; the
elsebranch fails loudly if it does not. - 41-44Check that a negative deposit is refused.
Grow it by adding an interest method, a statement function that prints the history, and a test for every new rule before you write the rule. Then write the README: what it does, how to run it, and what you would improve.
Common mistakes
β Starting with a project that is far too big
A social network, a full online shop or a 3D game has dozens of subsystems. You lose momentum and finish nothing. Shrink the idea until the first version fits in a few sessions, and treat the rest as stretch goals.
β Copying a tutorial and calling it a project
Following a video step by step teaches typing, not design. After finishing a tutorial, change something: add a feature from the checklist that the tutorial did not cover, or rebuild it from memory with different data.
β Mixing input, logic and printing in one block
When a function reads input, calculates and prints in the same place, you cannot test it. Pass values in, return values out, and keep input() and print() at the edges, as the starters above do.
β Using floats for money
Values such as 0.1 and 0.2 have no exact binary form, so totals drift. Keep money in whole cents or use Decimal, and format only for display.
β Never finishing the last twenty percent
Error messages, a README, a few tests and a clean folder take time but are what turn a script into a project. Add them to the checklist from the start so they are not an afterthought.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Why is it good to write the feature checklist before coding?
Q2. In the to-do starter, why does run return a string instead of printing?
Q3. Why does the expense splitter use integer cents?
Q4. What does passing a seed to random.Random(seed) achieve?
Q5. What is a dry-run mode for?
Q6. In minimax for tic-tac-toe, what does the recursion assume?
Frequently asked questions
Which project should I build first?
+Pick the theme that matches something you already enjoy, then start with the first idea in it. The runnable starter for each theme is a good first version. If you are unsure, the to-do manager or the word-frequency counter are the gentlest.
How many projects do I need?
+There is no magic number. Two or three finished, documented projects of different kinds teach more than many unfinished ones. Quality and completeness matter more than quantity.
Can I use libraries or should I stick to the standard library?
+Use the standard library to learn the fundamentals, then add libraries where they genuinely help, such as pandas for data or a web framework for apps. Check that a library is maintained and note it in your README.
What if I get stuck halfway?
+Shrink the problem. Write a tiny script that does only the part you are stuck on, print values to see what is happening, and read the traceback from the bottom. The debugging lesson has more techniques.
How do I show my projects to others?
+Put the code in a public repository with a clear README, and explain what the project does and what you decided. The portfolio and GitHub lesson walks through this step by step.
Key takeaways
- βChoose projects you can describe in one sentence and finish in a few sessions.
- βGive every project a goal, skills list, feature checklist and stretch goal.
- βBuild a thin end-to-end version first, then add one checklist item at a time.
- βKeep logic in functions that take and return values; keep input and printing at the edges.
- βStore money as integer cents or
Decimal, seed randomness for repeatable tests, and add a dry-run mode to anything that changes files. - βFinish the last twenty percent: errors, tests and a README turn a script into a project.