00.9 Working Like an Engineer: Debugging, Asking for Help and Learning Habits
Technical skill gets you hired; working habits are what keep you employed. This lesson is about the unglamorous half of engineering: how software actually gets built day to day, how to debug a problem systematically instead of randomly changing things, how to read an error message like it was written for you, how to search and ask for help in a way that gets answers, how to use AI assistants without being fooled by them, and the small daily habits that turn "I watched a tutorial" into "I can build this myself". It ends with a realistic plan for the rest of this learning path and a self-assessment that tells you where to start.
What you'll learn
- How professional software work actually flows: tickets, branches, pull requests, code review, standups and estimates — and what "done" and "tested" really mean
- How to read code you did not write, and why naming, comments and READMEs are part of the job
- Debugging as a method: the observe–hypothesise–experiment–conclude loop, reproducing and minimising bugs, bisecting with
git bisect, changing one thing at a time, and telling flaky bugs from real ones - How to read a Python traceback line by line, plus a catalogue of the first errors every beginner meets and what each usually means
- How to search effectively, how to read Stack Overflow and GitHub issues critically, and how to ask a question (or write a bug report) that actually gets answered — including the minimal reproducible example
- How to use AI coding assistants well: what they are good at, what they get wrong, the verify-before-trust routine, and why you must never paste secrets or private data into them
- The habits that compound: a
notes/journal, daily practice, building small projects, reviewing your own diffs, spaced repetition and learning in public - A realistic plan for Modules 00–14, a self-assessment quiz that places you (skip / skim / study), and professional basics: async communication, time and scope, security responsibilities, licences and accessibility
What you don't need
- Any programming experience beyond what Modules 00.1–00.8 cover: a working terminal, git basics, and comfort opening files. Python itself arrives in Module 01A — this lesson uses tiny Python snippets only to show what errors look like.
- An API key, an account, or any paid tool. Everything here works offline with a terminal, a text editor and git. Where AI assistants are discussed, no assistant is required: the habits apply to any tool, including none.
Setup
No API key needed. You need the terminal and text editor set up in lesson 00.1, and the ai-path workspace folder that lesson created (~/code/ai-path/). The exercises use a scratch folder inside it, and one exercise uses a notes/ folder — the running thread of this module. Python is used only for a few tiny examples; if you have it (python3 --version), run them, otherwise read the outputs.
What you must be able to do after this lesson#
- Describe how a ticket moves from branch to pull request to done
- Debug with the observe, hypothesise, experiment, conclude loop
- Read a Python traceback line by line
- Write a minimal reproducible example and ask a good question
- Verify AI assistant output before trusting it
- Plan your own route through the path
Why this matters for an AI engineer#
Every later module in this path assumes you can work like a professional: read an error and fix it, search before asking, verify what a tool tells you, and keep learning deliberately. These habits matter more in AI engineering than in most fields, because the tools are new, the documentation moves fast, and a confident wrong answer is the default failure mode of both search engines and chatbots.
| You'll hear... | You'll understand it after... |
|---|---|
| "Can you pick this up? Estimate it for the sprint." | Part 1 and 8.2 |
| "It's not working — any ideas?" (and nothing else) | Part 2 and 4.4 |
| "Read the traceback from the bottom up." | 3.1 |
"Have you tried git bisect?" |
2.4 |
| "Please open an issue with a minimal reproducible example." | 4.3 |
| "Don't paste that into ChatGPT — it has customer data in it." | 5.4 |
| "The assistant's code uses an API that doesn't exist." | 5.2 |
| "I keep a TIL log." | 6.1 |
| "Which module should I do next?" | Part 7 |
Part 1: How software gets built day to day#
1.1 The vocabulary of a working day#
If you have only ever written programs alone, the vocabulary of professional software work can feel like a foreign language. Here is the cast, in the order work usually flows:
- Ticket (or issue): a unit of work — a bug report, a feature request, a chore. On GitHub it is an Issue; in other trackers it might be a Jira ticket or a Linear item. A good ticket says what should happen, what happens instead, and how to reproduce it.
- Branch: your private copy of the code's history where you make changes without affecting anyone else (lesson 00.3).
- Pull request (PR): the request to merge your branch into the main codebase. It is also where review happens — humans (and increasingly AI assistants) read your diff before it lands.
- Code review: a colleague reading your diff and leaving comments: bugs, unclear names, missing tests, style. Review is not an interrogation; it is how knowledge spreads and defects die cheaply.
- Standup (or stand-up meeting): a short daily sync — "what I did, what I'm doing, what's blocking me". Its purpose is surfacing blockers, not status theatre.
- Estimate: a guess at how long a ticket will take, expressed in time or story points. Estimates are always uncertain; seniors give ranges and say what the estimate assumes.
- Sprint: a fixed planning window (often one or two weeks) in teams that work in iterations.
None of this is bureaucracy for its own sake. Each artefact exists because teams of people need to know what is being built, who is building it, whether it is any good, and what happens when it breaks in production.
1.2 "Done" means tested and reviewed#
In school, "done" often means "the program ran once on my machine". In a team, done means several stricter things:
| School version of done | Professional version of done |
|---|---|
| It ran once and printed something | It runs correctly on the cases that matter, including edge cases, and you can show how you checked |
| It works on my laptop | It works on a clean machine / in CI, with dependencies pinned and steps written down |
| Nobody else has seen it | A teammate reviewed the diff and you addressed the comments |
| The demo worked | Tests exist that will catch the next person who breaks it |
| I know it works | You can explain why it works, and what it does when things go wrong |
Two consequences follow. First, a big part of the job is making your work checkable: small diffs, clear commit messages, tests, and a PR description that says what changed and why. Second, "it works" is a claim that needs evidence — output, a test run, a screenshot, a log line. Engineers who say "should work" get asked "how do you know?"
What "tested" means concretely: a test is code that checks code — you write an input, state the expected result, and the check fails loudly when the code drifts from it. Tests exist to catch regressions: the bug someone reintroduces next month while fixing something else. The smallest version needs no framework at all — Python's built-in assert compares expected against actual:
def apply_discount(price: float, percent: float) -> float:
return round(price * (1 - percent / 100), 2)
def test_apply_discount():
assert apply_discount(100.0, 10) == 90.0 # expected vs actual
assert apply_discount(49.99, 0) == 49.99 # edge case: no discount
test_apply_discount() # silent = passed; AssertionError = failedRun it and a passing test prints nothing; a failing one raises AssertionError showing the mismatch. Real projects use a test runner — pytest discovers test_* functions like this one automatically, with fixtures and reporting on top (01B.8) — but the assert-first habit is identical either way.
1.3 Reading code you did not write#
Sooner or later you will open a file you didn't write — a colleague's module, a library's source, code an AI assistant generated last week, or your own code from six months ago that might as well have been written by a stranger.
Reading unfamiliar code is a skill with a method:
- Read the names first. Good names carry most of the meaning.
calculate_invoice_totaltells you what a function does before you read a line of its body. When names are bad, you must reconstruct intent from behaviour — which is why naming well is a professional duty, not a style preference. - Find the entry point. Where does execution start? What calls this function? Who calls it? Tools help: your editor's "find references",
grepfor the function name, or the test file that exercises it. - Follow the data. Pick the input that matters and trace it: where does it come from, what transforms it, where does it end up?
- Read the tests. Tests are executable documentation. They show the intended behaviour, the edge cases the author cared about, and how to run the code.
- Run it. The fastest way to understand code is often to run it with inputs you choose and watch what happens. A debugger or print statements turn "I think it does X" into "it does X".
Comments and documentation earn their place by explaining why, not what — the code already says what it does. # tax is added after discount per finance rule FR-12 is valuable; # increment i above i += 1 is noise. READMEs serve the person arriving cold: what the project is, how to install it, how to run it, how to test it.
1.4 Small steps beat big bangs#
Every professional habit in this lesson pushes the same direction: small, verifiable increments. A 400-line PR is unreviewable; a bug fix hidden inside a refactor is un-debuggable; a "quick fix" that also renames three functions is a trap for whoever bisects it later. Small steps also protect you: when something breaks, git diff shows exactly what you changed since it last worked.
Part 2: Debugging is a method, not a mood#
Debugging is the highest-leverage skill in this lesson, because almost everything else you will ever build will break. The difference between a beginner and a professional is not that the professional's code never breaks — it is that the professional has a process that finds the cause quickly, and a beginner has a mood that involves changing things until something works.
2.1 The scientific loop#
Debugging is applied science. You are running an experiment on your own program:
flowchart TD
A["Observe: what exactly happens?<br/>(error message, wrong output, expected vs actual)"] --> B["Hypothesise: what could cause this?<br/>list 2-3 candidates, most likely first"]
B --> C["Experiment: change ONE thing<br/>that tests the top hypothesis"]
C --> D{"Result matches<br/>the hypothesis?"}
D -- "yes" --> E["Conclude: you found the cause<br/>write it down, apply the real fix"]
D -- "no / inconclusive" --> F["Record what you tried<br/>and what happened"]
F --> B
E --> G{"Bug fixed<br/>and verified?"}
G -- "no" --> A
G -- "yes" --> H(["Done: commit the fix<br/>with a message that says why"])The rules that make this work:
- Observe before theorising. Write down what actually happens: the exact error text, the exact wrong output, what you expected instead. "It's broken" is not an observation; "
totalprints12.0but should be21.6" is. - Hypothesise before experimenting. List your candidate causes, most likely first. If you can't name a hypothesis, you don't yet understand the system — go back to reading the code or the docs.
- Change one thing at a time. If you change three things and the bug disappears, you don't know which change fixed it — and the other two may have introduced new bugs. This is the single most common debugging failure.
- Record what you tried. Keep a running note (a
notes/file, a text file, even comments you delete later). When you come back to a stubborn bug after lunch, "what did I already try?" is the first question — and memory is unreliable.
A supporting habit worth naming: rubber-duck debugging — explaining the problem out loud, sentence by sentence, to a patient colleague, your notes/ file, or a literal rubber duck. It sounds silly and it works, because forcing the bug into words surfaces the assumption you didn't know you were making ("wait — split("|") gives me a list, and I'm unpacking it as if it were four separate values"). The name comes from the original story of a programmer who debugged by narrating the code to a rubber duck; the duck's great virtue is that it has never once answered with a wrong guess.
2.2 Reproduce first, then minimise#
Two moves precede almost every real debugging session:
Reproduce reliably. A bug you cannot make happen on demand is a bug you cannot fix. Find the smallest set of steps or inputs that triggers it, every time. If it only fails "sometimes", that is itself a clue — flaky bugs have causes (timing, ordering, randomness, state left behind by an earlier run) and 2.6 is about them. If you cannot reproduce it at all, suspect the environment: different data, different versions, different machine.
Minimise the case. Once it reproduces, shrink it. Delete unrelated parts of the input, the code path, the configuration — one at a time — until removing anything else makes the bug vanish. The classic example: a 10,000-line data file triggers a crash; you binary-search the file and discover row 4,317 has a stray quote. A minimal case is easier to reason about, faster to run, and — crucially — becomes your minimal reproducible example when you ask for help (4.3).
2.3 Worked example: the invoice bug#
Here is the loop in action on a deliberately buggy function. The ticket says: "line_total(10.0, 2, 10) returns 12.0, but 2 × $10.00 with 10% off and 20% tax should be 21.60."
# invoice.py — computes a line total. Contains a planted bug.
def line_total(price, qty, discount_pct):
subtotal = price * qty
discounted = subtotal - discount_pct # discount_pct is a PERCENT
total = discounted * 1.20 # 20% sales tax
return round(total, 2)
if __name__ == "__main__":
print(line_total(10.0, 2, 10)) # 2 x $10.00, 10% off, then taxRunning it gives 12.0 — reproduced. Now the hypotheses, most likely first:
- The discount is being subtracted as a raw number instead of a percentage of the subtotal.
- The tax rate is wrong.
- The rounding is wrong.
The cheapest experiment that tests hypothesis 1 is to print the intermediate values — temporary print() probes, removed before committing:
# invoice_debug.py — same function with temporary print() probes.
def line_total(price, qty, discount_pct):
subtotal = price * qty
print(f"debug: subtotal={subtotal}")
discounted = subtotal - discount_pct
print(f"debug: discounted={discounted} (discount_pct={discount_pct})")
total = discounted * 1.20
print(f"debug: total={total}")
return round(total, 2)
if __name__ == "__main__":
print("result:", line_total(10.0, 2, 10))debug: subtotal=20.0
debug: discounted=10.0 (discount_pct=10)
debug: total=12.0
result: 12.0The probe shows discounted=10.0: the code subtracted the number 10 (a percent) from 20.0, instead of subtracting 10% of 20.0. Hypothesis 1 confirmed; the others are irrelevant. The fix:
# invoice_fixed.py — discount_pct is a percent: divide by 100.
def line_total(price, qty, discount_pct):
subtotal = price * qty
discounted = subtotal * (1 - discount_pct / 100)
total = discounted * 1.20
return round(total, 2)
if __name__ == "__main__":
print(line_total(10.0, 2, 10))21.6Three lessons in miniature: the observation was already in the ticket; the hypothesis ranked the likely causes; the experiment (two print lines) pinpointed which one was true in seconds. Note also what the fix is not: it is not "try * instead of - and see". It is a one-line change justified by evidence.
2.4 Bisect: let binary search find the culprit#
Some bugs are regressions: yesterday the program worked, today it doesn't, and thirty commits landed in between. Testing each commit by hand is O(n); bisecting is O(log n). The idea is the same binary search you know from sorted lists: you have a "good" point and a "bad" point in history, check the middle, and discard half the range each step.
You can bisect by hand: git log to list recent commits, git checkout <hash> to visit one, run the program, decide good or bad, repeat. Or let git do the bookkeeping with git bisect (official docs). Here is a real session on a six-commit repo where a tax calculation broke in commit c4 — the repo is invented for the demo, but every line of output below is real git output, and the collapsible block after the session recreates the repo exactly (same hashes):
$ git bisect start
status: waiting for both good and bad commits
$ git bisect bad # HEAD (c6) prints total=10.1 — wrong
status: waiting for good commit(s), bad commit known
$ git bisect good 368361b # c1 is known good
Bisecting: 2 revisions left to test after this (roughly 1 step)
[c808b160fae28acda3ec9d8bcb61f88981f361d6] c3: add tax
# bisect checked out c3; run the program:
$ python3 calc.py
total= 11.0
$ git bisect good # 11.0 is correct
Bisecting: 0 revisions left to test after this (roughly 1 step)
[4a9a2a50fb5fa93aba7fe45cce5493ed25c120f6] c5: label output
# bisect checked out c5:
$ python3 calc.py
total= 10.1 (excl. fees)
$ git bisect bad # 10.1 is wrong
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[33abf82601c8c52011d2b7ca59186d729c17c96e] c4: tax refactor
# bisect checked out c4:
$ python3 calc.py
total= 10.1
$ git bisect bad
33abf82601c8c52011d2b7ca59186d729c17c96e is the first bad commit
commit 33abf82601c8c52011d2b7ca59186d729c17c96e
Author: Learner <learner@example.com>
Date: Sun Jan 4 10:00:00 2026 +0000
c4: tax refactor
calc.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
$ git bisect reset
Previous HEAD position was 33abf82 c4: tax refactor
Switched to branch 'main'Three tests narrowed six commits to the exact culprit: c4: tax refactor — a commit whose message gave no hint that it broke anything, which is exactly why git log reading plus bisect beats guessing. Two professional notes:
git bisect run <cmd>automates the loop when you have a command that exits 0 for "good" and non-zero for "bad" (a test, a script that checks the output). Lesson 00.3 coversgit bisectawareness; the git book's debugging chapter has the full treatment.- Always finish with
git bisect reset— it returns you to the branch you started on. Forgetting leaves you in a detached-HEAD state (explained in 00.3) that confuses the nextgit status.
Try it: recreate this exact repo
Run this script in a scratch folder (mktemp -d on macOS/Linux, or any new folder — the script needs bash, so on Windows use WSL or Git Bash). It builds the six commits above — same messages, same calc.py contents, same pinned dates and identity — so git log --oneline shows the same hashes as the session (368361b through 7470e07). Then re-run the bisect commands from the session yourself.
# recreate-bisect-demo.sh — builds the six-commit demo repo from 00.9 §2.4
set -e
# Never read the machine's real git config; pin a throwaway identity and dates
# so the commit hashes are reproducible.
export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null TZ=UTC
export GIT_AUTHOR_NAME="Learner" GIT_AUTHOR_EMAIL="learner@example.com"
export GIT_COMMITTER_NAME="Learner" GIT_COMMITTER_EMAIL="learner@example.com"
git init -b main -q . # git older than 2.28: `git init` then `git checkout -b main`
commit() { # $1 = message, $2 = date; new calc.py content on stdin
cat > calc.py
git add calc.py
GIT_AUTHOR_DATE="$2" GIT_COMMITTER_DATE="$2" git commit -qm "$1"
}
commit "c1: base total" "2026-01-01T10:00:00+00:00" <<'EOF'
BASE = 10
print("total=", BASE)
EOF
commit "c2: discount field" "2026-01-02T10:00:00+00:00" <<'EOF'
BASE = 10
DISCOUNT = 0
print("total=", BASE - DISCOUNT)
EOF
commit "c3: add tax" "2026-01-03T10:00:00+00:00" <<'EOF'
BASE = 10
DISCOUNT = 0
TAX_RATE = 0.1
total = round((BASE - DISCOUNT) * (1 + TAX_RATE), 1)
print("total=", total)
EOF
commit "c4: tax refactor" "2026-01-04T10:00:00+00:00" <<'EOF'
BASE = 10
DISCOUNT = 0
TAX_RATE = 0.1
total = BASE - DISCOUNT + TAX_RATE
print("total=", total)
EOF
commit "c5: label output" "2026-01-05T10:00:00+00:00" <<'EOF'
BASE = 10
DISCOUNT = 0
TAX_RATE = 0.1
total = BASE - DISCOUNT + TAX_RATE
print("total=", total, "(excl. fees)")
EOF
commit "c6: done marker" "2026-01-06T10:00:00+00:00" <<'EOF'
BASE = 10
DISCOUNT = 0
TAX_RATE = 0.1
total = BASE - DISCOUNT + TAX_RATE
print("total=", total, "(excl. fees)")
print("done")
EOF
git log --onelineOn your own repos you would never do this — real dates and your real name are exactly what you want. The pinned identity and dates exist only so a demo like this one is byte-for-byte reproducible.
2.5 "What changed?" — environment vs code#
Before deep debugging, ask the cheapest question: what changed since it last worked? The answer is usually one of:
- Your code changed.
git statusandgit diffshow uncommitted edits;git log -pshows recent commits;git stash listshows set-aside work. - Your environment changed. A new Python version, a package upgraded (
uv pip list, or check the lockfile diff), an environment variable edited, a different working directory, a file moved or renamed, the network down, a certificate expired, the clock wrong. - The data changed. The bug only appears on inputs you haven't tried before — the "works on the demo data" trap.
A worked git diff from the same scratch repo, after editing calc.py:
$ git status --short
M calc.py
$ git diff
diff --git a/calc.py b/calc.py
index 066099f..fe6bfa2 100644
--- a/calc.py
+++ b/calc.py
@@ -1,6 +1,5 @@
BASE = 10
DISCOUNT = 0
TAX_RATE = 0.1
-total = BASE - DISCOUNT + TAX_RATE
-print("total=", total, "(excl. fees)")
-print("done")
+total = BASE - DISCOUNT + TAX_RATE * 10
+print("total=", total)Reading a diff is a core engineering skill: - lines are what was there, + lines are what replaced them, and the @@ hunks tell you where. If the bug appeared right after pulling a colleague's branch, git diff main...HEAD (or reading the PR's "Files changed" tab on GitHub) is your first stop.
The same machinery makes experiments cheap — the habit the debugging loop depends on. Most of debugging is trying things: a probe print, a tweaked constant, a config change, a deleted line. Git means none of them need to be permanent: git status and git diff show exactly what an experiment touched, git restore <file> throws it away (the older spelling is git checkout -- <file>), and git stash parks it if you might want it back. Experiment freely because undo is one command — the professional attitude is the opposite of the beginner fear that touching the code might break it worse.
2.6 When it only fails sometimes: flaky bugs#
A flaky bug fails intermittently — a test that passes alone but fails in the suite, a crash that happens once a day, a race between two requests. Flaky bugs are the most expensive kind because they erode trust in your whole test suite ("oh, that test is just flaky") and they hide real defects.
The causes are a known shortlist:
| Cause | Typical signature | First thing to check |
|---|---|---|
| Timing / race conditions | Fails under load, passes alone | Shared state, ordering assumptions, sleeps used as synchronisation |
| Shared mutable state | Fails only after another test ran first | Global variables, class attributes, singletons, caches |
| Randomness without a seed | Different failure each run | random/secrets/network data used unseeded |
| Time and dates | Fails at midnight, month end, DST | Code assuming "today", time zones, datetime.now() |
| External dependencies | Fails when network/API is slow or down | Real network calls in tests, third-party services |
| Order dependence | Fails in a different sequence | Tests that assume they run in a particular order |
| Leftover state on disk | Fails on second run, passes on fresh clone | Temp files, caches, .pyc, database rows not cleaned up |
Debugging a flaky bug adds one rule to the loop: make it fail reliably first. Run the failing scenario in a loop (for i in $(seq 1 50); do python3 test.py || break; done), stress it, or add the suspected delay. A bug you can trigger on demand is debuggable; a bug that happens "rarely" is a lottery ticket.
2.7 Print debugging vs a real debugger#
Two tools dominate day-to-day debugging, and professionals use both:
- Print/log debugging: add
print(f"x={x}")(or aloggingcall — see below) at the points you want to observe, run, read the values, remove or downgrade the prints. Cheap, always available, works everywhere including production logs, and often faster than a debugger for "what is this value here?" questions. Done well — printing with labels andrepr()so types are visible (discounted=10.0vsdiscounted=10) — it is a legitimate professional technique, not a beginner crutch. - A real debugger:
breakpoint()in Python drops you intopdb, where you can pause at a line, inspect every variable, step line by line, and evaluate expressions in the live context. VS Code's debugger does the same with a visual UI (breakpoints in the gutter, a variables pane, a call stack). Debuggers shine for "how did we get here?" questions — the call stack shows the path that led to the bug.
The honest guidance: start with prints for values, reach for the debugger for control flow. And in real projects, temporary prints become logging.debug(...) calls — structured, levelled, removable — rather than living print() statements. Python's logging module and pdb are covered properly in Module 01A, lesson 8 (errors, debugging and logging) and Module 01B, lesson 10 (logging for services); VS Code's own debugging docs are at code.visualstudio.com/docs/editor/debugging.
A first pdb session. Use the buggy invoice.py from 2.3 in a scratch folder and start it under the debugger with python3 -m pdb invoice.py (or put breakpoint() on any line and run normally). You get a (Pdb) prompt; type a command and press Enter. Here is a session that sets a breakpoint on the function, steps through it and asks for values (file paths shortened to ...):
$ python3 -m pdb invoice.py
> .../invoice.py(3)<module>()
-> def line_total(price, qty, discount_pct):
(Pdb) break line_total
Breakpoint 1 at .../invoice.py:4
(Pdb) continue
> .../invoice.py(4)line_total()
-> subtotal = price * qty
(Pdb) next
> .../invoice.py(5)line_total()
-> discounted = subtotal - discount_pct # discount_pct is a PERCENT
(Pdb) p subtotal
20.0
(Pdb) p discount_pct
10
(Pdb) next
> .../invoice.py(6)line_total()
-> total = discounted * 1.20 # 20% sales tax
(Pdb) p discounted
10.0
(Pdb) quitThe session above follows a real run on Python 3.14 with the machine-specific paths replaced by ..., which is why it is labelled illustrative; line numbers depend on how you save the file. It shows the same fact the print() probes showed — discounted is 10.0, not 18.0 — but without editing the code. The commands you will use ninety per cent of the time:
| Command | Short | What it does |
|---|---|---|
next |
n |
Run the current line; step over any function it calls |
step |
s |
Run the current line; step into a function it calls |
continue |
c |
Run until the next breakpoint (or the end) |
print expr |
p expr |
Show a value; pp expr pretty-prints big structures |
list |
l |
Show the source around the current line (ll shows the whole function) |
where |
w |
Print the call stack — "how did I get here?" |
up / down |
u / d |
Move between stack frames to inspect the caller's variables |
break N or break func |
b |
Set a breakpoint at line N or at a function |
quit |
q |
Leave the debugger and stop the program |
Two more tricks: run a script as python3 -m pdb script.py and, if it crashes with an uncaught exception, pdb opens at the crash line (a post-mortem) so you can inspect the variables that caused it; and the environment variable PYTHONBREAKPOINT=0 makes every breakpoint() call do nothing, which is a safe way to run a program that still contains one.
Part 3: Reading errors like a professional#
3.1 Anatomy of a traceback#
When Python code fails, it prints a traceback — and beginners' universal mistake is to read only the last line, or worse, to panic and start editing. A traceback is structured, and it is telling you a story. Here is the whole artefact the exercises in this lesson use: a small support-ticket report tool, run against a data file where one row is missing its priority field.
tickets.txt — one ticket per line, fields separated by | (id, customer, subject, priority):
T-101|acme|cannot log in|high
T-102|globex|invoice question|normal
T-103|initech|site down|urgent
T-104|umbrella|feature requestbuggy_report.py — loads the rows into dictionaries, scores each ticket by priority and prints a ranked report:
# buggy_report.py — loads tickets.txt, ranks by priority, prints a report.
# Run: python3 buggy_report.py (expects tickets.txt in the same folder)
def load_tickets(path):
tickets = []
with open(path) as f:
for line in f:
if line.strip():
ticket_id, customer, subject, priority = line.strip().split("|")
tickets.append({
"id": ticket_id,
"customer": customer,
"subject": subject,
"priority": priority,
})
return tickets
def priority_score(ticket):
pri = ticket["priority"].lower()
if pri == "urgent":
return 4
if pri == "high":
return 3
if pri == "normal":
return 2
return 1
def main():
tickets = load_tickets("tickets.txt")
ranked = sorted(tickets, key=priority_score, reverse=True)
for t in ranked:
print(f"{t['id']} score={priority_score(t)} {t['subject']}")
main()Save both files in a scratch folder and run python3 buggy_report.py. It crashes on the last row — and this is the real traceback it prints (captured on Python 3.14; on 3.11–3.13 the frames and message are identical, though the caret/tilde underlining's exact style varies a little by version — and on 3.10 and older there are no markers at all):
Traceback (most recent call last):
File "buggy_report.py", line 34, in <module>
main()
~~~~^^
File "buggy_report.py", line 29, in main
tickets = load_tickets("tickets.txt")
File "buggy_report.py", line 9, in load_tickets
ticket_id, customer, subject, priority = line.strip().split("|")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 4, got 3)(The File lines show the path on the machine that ran it; only the file name, line numbers and the message matter to you.)
Read it bottom-up:
- The last line is the verdict.
ValueError: not enough values to unpack (expected 4, got 3)— the operation failed because it needed 4 values and got 3. That single line already narrows the cause enormously: somewhere,split("|")produced 3 fields where 4 were expected. - The
File/line/inframes above are the journey. Each frame says: "while executing this line of this function, the next thing was called". Here the story is:main()(line 29) calledload_tickets()(line 9), which tried to unpack a split line into four names and failed. The top frame (<module>→main()) is just how the program started. - The source line and the
^^^^marker show the exact code that failed. Python 3.11+ even underlines the precise expression (the exact marker style —^^^^,~~~~^^— varies a little between versions; older Pythons show just the source line). - "During handling of the above exception…" (when present) means a second error happened while Python was already reporting the first — often the real story is the first traceback, and the second is your error handler failing. Read both.
Two habits make tracebacks fast to read: read the exception type first (ValueError, KeyError, TypeError — each is a different family of cause, covered in 3.2), and find the deepest frame that is your code — library frames above it are context, but the bug is almost always in the frame where your code called into the library.
The fix — the version exercises 1, 2 and 8 work from — is fixed_report.py: identical to buggy_report.py except that load_tickets skips malformed rows (with a warning) instead of crashing. The two files differ only inside that one function; diff buggy_report.py fixed_report.py shows the whole change, which is itself a good habit to build.
# fixed_report.py — same tool, tolerant of short/malformed rows.
def load_tickets(path):
tickets = []
with open(path) as f:
for line in f:
if not line.strip():
continue
parts = line.strip().split("|")
if len(parts) != 4:
print(f"skipping malformed line: {line.strip()!r}")
continue
ticket_id, customer, subject, priority = parts
tickets.append({
"id": ticket_id,
"customer": customer,
"subject": subject,
"priority": priority,
})
return tickets
def priority_score(ticket):
pri = ticket["priority"].lower()
if pri == "urgent":
return 4
if pri == "high":
return 3
if pri == "normal":
return 2
return 1
def main():
tickets = load_tickets("tickets.txt")
ranked = sorted(tickets, key=priority_score, reverse=True)
for t in ranked:
print(f"{t['id']} score={priority_score(t)} {t['subject']}")
main()Running it prints the warning for T-104, then the three valid tickets ranked by score — urgent first:
skipping malformed line: 'T-104|umbrella|feature request'
T-103 score=4 site down
T-101 score=3 cannot log in
T-102 score=2 invoice question3.2 The first errors every beginner meets#
Almost every debugging session starts with one of these. Learn the shape of each — what it means and what to check first — and most errors stop being scary.
| Error (last line of output) | What it usually means | First thing to check |
|---|---|---|
command not found (exit 127) |
The shell can't find the program: typo, not installed, or not on PATH |
which <cmd> / command -v <cmd>; re-read the command for typos; was it installed in a different shell or location? |
Permission denied (exit 126) |
Tried to run a file without execute permission, or write where you can't | ls -l file — does it start with -rw instead of -rwx? chmod +x if it's a script you own |
ModuleNotFoundError: No module named 'x' |
Python can't find the module: not installed, typo, or wrong environment | Is it installed? (pip show x / uv pip list) Are you in the right venv? (which python3, sys.executable) Is the name spelled right? |
IndentationError / SyntaxError |
Python couldn't even parse the file: bad indentation (Python is whitespace-sensitive), missing : after if/for/def, unclosed (, [, { or quote |
The line number points near the problem — often the previous line (a missing colon shows up on the next one) |
KeyError: 'subject' |
A dictionary lookup failed: the key doesn't exist | Print the dict's keys; is the key spelled/cased right? Should you use .get() with a default? |
IndexError: list index out of range |
Tried to read past the end (or before the start) of a list | len() the list; is the index off-by-one? Is the list empty when you assumed it wasn't? |
TypeError: can only concatenate str (not "int") to str |
An operation got the wrong type of value | What type is each operand? type(x) — did a string arrive where a number was expected (e.g. unconverted input)? |
AttributeError: 'NoneType' object has no attribute 'x' |
You called a method/attribute on None — usually a function returned None where you expected a value |
What does the function return on the failing path? Did you forget return? |
FileNotFoundError: [Errno 2] No such file or directory |
A path doesn't exist relative to where you're running from | pwd — are you in the directory you think? ls the path; is it data.csv vs ./data/data.csv? |
json.decoder.JSONDecodeError: ... |
The text isn't valid JSON: trailing comma, single quotes, comments, a truncated body, or an HTML error page where JSON was expected | Print the first 200 characters of what you're parsing; is it actually JSON? (A 401 HTML page is a classic surprise) |
OSError: [Errno 48] Address already in use (Linux: Errno 98; Windows: [WinError 10048]) |
Something already listens on that port | macOS/Linux: lsof -i :8000; Windows PowerShell: Get-NetTCPConnection -LocalPort 8000 (or netstat -ano | findstr :8000) to find the process; is a previous run of your server still alive? |
HTTP 401 / 403 / 404 / 429 |
From 00.6: 401 = not authenticated (bad/missing key), 403 = authenticated but not allowed, 404 = wrong URL/method, 429 = rate limited | Check the key and auth header → check permissions → check the URL path verbatim → slow down and retry |
A taste of the real outputs — each is the last line that matters:
$ python3 -c "import not_a_real_module"
ModuleNotFoundError: No module named 'not_a_real_module'
$ python3 -c "ticket = {'id': 'T-1', 'priority': 'high'}; print(ticket['subject'])"
KeyError: 'subject'
$ python3 -c "import json; print(json.loads('{\"id\": \"T-1\",}'))"
json.decoder.JSONDecodeError: Illegal trailing comma before end of object: line 1 column 13 (char 12)(The Illegal trailing comma wording is Python 3.13+; on 3.11–3.12 the same input reports Expecting property name enclosed in double quotes: line 1 column 14 (char 13) — either way it's a JSONDecodeError on invalid JSON, which is the part that matters.)
$ ./noexec.sh
bash: ./noexec.sh: Permission denied# The "wrong environment" trap, demonstrated:
# You ran `pip install requests` — but `python3` finds no module:
# ModuleNotFoundError: No module named 'requests'
# while `python3 -c "import sys; print(sys.executable)"` shows a
# different interpreter than the one pip installed into.
# Check WHICH python you're using before believing "it's not installed".3.3 Stack traces in other languages#
The format differs, the reading strategy doesn't. A JavaScript Error: Cannot read properties of undefined (reading 'map') with at processRows (report.js:42:11) is the same story as a Python traceback: message = verdict, frames = journey. Java stack traces list at com.example... frames; Go panics print goroutine stacks; Rust panics print thread 'main' panicked at src/main.rs:12:5. In every case: read the message, then walk the frames to the deepest frame in code you own. Lesson 01A.11 has a side-by-side comparison if you're coming from another stack.
Part 4: Searching and asking for help#
Deep-dive
Engineers spend a large fraction of their time not writing code but finding out how — reading docs, searching error messages, asking people who know. Done badly this feels like begging; done well it is a professional skill with its own technique.
4.1 Search like a professional#
The difference between "no results" and "the answer in 30 seconds" is almost always the query.
Search the exact error, quoted. Error messages are unique fingerprints. "not enough values to unpack" python beats python error. Quotation marks force an exact phrase; without them the engine "helpfully" searches each word separately and buries the match.
Add the tool and the version. pandas KeyError groupby version 2.x is a different question from pandas KeyError — APIs change between major versions, and the top result for the wrong version will confidently mislead you. Include your version (python3 --version, pip show pandas) in the query and, when asking, in the question.
Official docs first, then the community. For "how do I do X", start at the project's official documentation — it's maintained, versioned and authoritative. For "why does X break", the community (Stack Overflow, GitHub issues) is where the war stories live. A good search order: official docs → the project's issue tracker → Stack Overflow → blog posts → AI assistants (with verification, Part 5).
Search GitHub issues for the project itself. If a library misbehaves, someone has probably reported it. Search repo:owner/name <symptom> on GitHub, or the project's issue tracker directly — a matching issue often contains the workaround, the maintainer's explanation, or "fixed in v2.3, upgrade".
Search your own notes. This is why 6.1 matters: the sixth time you hit Address already in use should take ten seconds because you wrote down the fix last month.
4.2 Reading Stack Overflow and GitHub issues critically#
The highest-voted answer is not always the right one. Stack Overflow rewards age and popularity; APIs move on. When you read an answer, check:
- The date and the versions. An answer from 2019 about
requestsmay be wrong forrequests2.32+. Look for the library version in the question and the answer's date. - The accepted answer vs the better answer. The green checkmark means "it worked for the asker", not "it's the best way". Read the other high-voted answers and the comments — the correction often lives there.
- Whether it applies to your case. Answers get upvoted for the common case; your edge case may need a different approach. The comments frequently contain "this doesn't work for X because…".
- The maintainer's voice. On GitHub issues, a comment from a maintainer or core contributor outweighs ten community guesses.
The same critical eye applies to GitHub issues: an issue titled "bug" may be closed as not planned or works as intended; an open issue may have a linked PR with the fix; a good first issue label marks beginner-friendly contributions (Module 14B touches contributing to open source).
4.3 The minimal reproducible example#
The single most important artefact in asking for help is the minimal reproducible example (MRE) — also called a minimal complete verifiable example (MCVE) or reprex. It is the smallest piece of code or steps that someone else can run to see the exact problem you see. Stack Overflow's help page puts it as: minimal (as little code as possible), complete (everything needed to reproduce, in the question itself), verifiable (you tested that it reproduces the problem).
Why it matters: a maintainer or helper who can run your MRE in two minutes will debug it for you; one who must reconstruct your 5,000-line app from a screenshot will not. The MRE is also how you debug — building it forces you through 2.2, and the act of minimising often reveals the bug before anyone answers.
An MRE has:
- The code (pasted as text, not a screenshot — images of code can't be copied, searched or run)
- The input that triggers it (the data, the command, the request)
- The expected output and the actual output (the error text, verbatim)
- The environment: OS, language/runtime version, library versions
4.4 The good question#
Combine the MRE with context and you get a question that gets answered. The template:
Title: <specific symptom + tool, e.g. "pandas groupby KeyError after upgrade to 2.2">
Environment: Python 3.13, pandas 2.2.3, macOS 15
What I expected: <one sentence>
What happened instead: <the exact error, pasted verbatim>
Minimal example:
<the smallest code that reproduces it>
What I already tried:
- <thing 1, and what it did>
- <thing 2, and what it did>
Question: <the one specific thing you're asking>Two rules from the classics still hold: describe the symptom, not your guess at the cause ("it returns None" beats "the function is broken"), and show what you tried (it prevents the answer "have you tried turning it off and on again" and signals you've done the work). For a bug report to a project, the same structure applies — plus a git bisect result if you have one, because "introduced in commit X" is worth a paragraph of debugging.
4.5 Communities and escalation#
Where to ask, in order of increasing specificity:
- The project's official channel: GitHub Discussions/Issues, the project's forum or Discord, the mailing list. This is where the people who wrote the code answer.
- Stack Overflow: for general language/framework questions with a clear MRE.
- Your team: a teammate, your tech lead, the person who wrote the module. Asking them is not a failure — it is the job. The professional move is to ask after you've reproduced, minimised and searched, and to ask in a way that respects their time (see 8.1).
When you ask a teammate, the same MRE discipline applies in miniature: "I'm seeing X when I do Y; I expected Z; I've tried A and B; can you look at C?" gets a faster answer than "it's broken, help". And when someone answers you, the follow-up is part of the craft: thank them, confirm the fix worked, and write the lesson into your notes/ so you never ask twice.
The whole escalation path, from "stuck" to "unblocked", in one picture:
flowchart TD
A["Stuck on a problem"] --> B["1. Reproduce it reliably<br/>same input, same failure?"]
B --> C["2. Minimise and bisect<br/>smallest case, git bisect if it is a regression"]
C --> D["3. Read the whole error<br/>and check what changed recently (git diff, git log)"]
D --> E["4. Search: exact error in quotes,<br/>tool name + version, official docs first"]
E --> F{"Found a fix or<br/>a matching issue?"}
F -- "yes" --> G["Try it; verify it fixes YOUR case"]
F -- "no" --> H["5. Ask an AI assistant<br/>with a minimal reproducible example"]
H --> I["6. Verify before trusting:<br/>run it, read it, test it, check the docs"]
I --> J{"Still stuck<br/>after a real effort?"}
J -- "no" --> K(["Keep going: you are<br/>learning by debugging"])
J -- "yes" --> L["7. Ask a teammate or the community<br/>with context: what you tried, versions, MRE"]
L --> M(["Most bugs end here:<br/>someone has seen it before"])Part 5: AI assistants and chatbots, used well#
You are learning to code in the era of AI assistants — tools like GitHub Copilot (an "AI coding agent" built into GitHub, VS Code, the CLI and other editors; plans and surfaces change often, so check github.com/features/copilot for the current state), Cursor, Claude, ChatGPT, and the coding agents covered deeply in lesson 08A.15. They are genuinely useful and genuinely dangerous in specific, learnable ways. This part is about using them as a tutor and pair programmer, not as an oracle.
5.1 What they are good at — and what they get wrong#
Good at: explaining concepts in five different ways until one clicks; generating boilerplate (a CLI argument parser, a config file, a test skeleton); translating between languages and idioms; writing tests for code you already have; refactoring small, well-specified changes; summarising long error messages and docs; brainstorming approaches; rubber-ducking (explaining your problem often reveals the answer mid-sentence).
Get wrong — reliably:
- Invented APIs. The model will produce a function signature, parameter name or library call that looks right and does not exist — especially for less popular libraries and for anything newer than its training data. This is called a hallucination, and it is the default failure mode, not an edge case.
- Outdated versions. It may teach you the API as of two years ago, or mix versions (
pandas1.x idioms in a 2.x world). - Subtle bugs. Code that runs but is wrong on edge cases — off-by-one, unhandled
None, mutable default arguments, missingawait. - Insecure code.
eval()where validation belongs, SQL built by string formatting, secrets in source, overly broad permissions. Module 12 is the security counterpart; treat every generated snippet as untrusted until reviewed. - Licence and provenance problems. Code reproduced from memory may derive from GPL or proprietary sources; generated code can also be a near-copy of something in the training data. If you ship it, you need to know what it is.
The pattern: assistants are excellent at plausible and unreliable at verified. Plausible is exactly what you don't want in code.
5.2 The verify-before-trust routine#
Treat every assistant response as a junior colleague's first draft — often right, sometimes confidently wrong. The routine:
flowchart LR
A["Ask the assistant<br/>for code or an explanation"] --> B["Read every line<br/>before running anything"]
B --> C["Run it in a scratch folder<br/>or your project, never blindly"]
C --> D{"Does it do<br/>what you asked?"}
D -- "no" --> E["Say what was wrong<br/>and ask again with specifics"]
E --> A
D -- "yes" --> F["Test it: edge cases,<br/>the failure paths, your real data shape"]
F --> G{"Tests pass and<br/>docs agree?"}
G -- "no" --> E
G -- "yes" --> H["Check versions and licences:<br/>is this API still current?<br/>may you use this code?"]
H --> I(["Only now: use it<br/>and understand why it works"])Concretely:
- Read it. Line by line. If you can't explain what a line does, you don't yet have code — you have a liability.
- Run it — in a scratch directory first for anything unfamiliar, then in your project.
- Test the edges. Empty input,
None, the boundary values, the failure path. Generated code is most often wrong exactly where you didn't look. - Check the docs. Does the API it used actually exist, with that signature, in your version? One look at the official docs page settles it. This is also the skill lesson 00.8 teaches — the assistant makes reading docs more important, not less.
- Check versions and licences. Is this the current API or a deprecated one? Is the licence compatible with what you're building?
5.3 Ask for a tutor, not a code dispenser#
The highest-value use of an assistant for a learner is as a tutor:
- Ask it to explain, then quiz you. "Explain how
git bisectworks, then ask me three questions to check my understanding." Explaining-to-yourself is the learning mechanism; the assistant is a patient audience. - Ask for the why, not just the what. "Why does this
TypeErrorhappen?" teaches more than "fix thisTypeError". - Ask for a hint before the answer. "I'm stuck on this bug — what's a good first experiment?" keeps you doing the debugging, which is where the skill lives.
- Use it to review your work. "Here's my solution — what's wrong with it or what edge cases am I missing?" is often more valuable than asking it to write the solution.
The code-dispensing mode ("write me a REST API for X") produces code you didn't write, don't understand and can't debug — which is exactly the position you were in before you started this path. Use that mode for scaffolding you will study, or not at all.
5.4 Secrets, private data and licences#
Two hard rules, no exceptions:
- Never paste secrets or private data into an assistant. That means API keys, passwords, tokens,
.envcontents, customer data, personal data (names, emails, IDs), proprietary code, or anything under NDA. The data you paste may be retained, logged, used for training (depending on the product and plan), or exposed in a breach. This is not hypothetical: it is the same reason 03.1 Part 3 is strict about keys, and why 12.4 exists. Redact first (sk-...,user@example.com→user_42), or describe the shape ("a JWT with three base64 parts") instead of pasting the value. - Check licences before you ship generated or copied code. MIT, Apache-2.0 and BSD are permissive; GPL and AGPL have copyleft obligations; "no licence" means all-rights-reserved. An assistant will happily reproduce GPL code into your proprietary project. When in doubt, check the source's licence, and prefer writing it yourself when the stakes are high.
5.5 The learning trap and workplace rules#
The deepest risk is not technical but educational: outsourcing the thinking. If the assistant writes every function, you will feel productive for weeks and then discover you cannot debug, review or extend anything without it — and interviews, code reviews and on-call pages don't come with an assistant. The defence is the tutor-mode habit above plus one rule: try first, ask second. Spend real effort on the problem — reproduce it, form a hypothesis, attempt a fix — then ask the assistant, ideally showing it what you tried. You will learn more from "here's what I tried and why it failed" than from a clean prompt, and the assistant's answer will be better targeted too.
Finally, workplace policy. Many employers have rules about which AI tools you may use, what code may be sent to external services, and whether generated code must be disclosed in review. Read your team's policy (often in AGENTS.md, CONTRIBUTING.md or an internal wiki) before pasting work code into any tool. When in doubt, ask. The assistant is a tool you use within the rules, not a loophole around them.
For the full treatment of coding agents — how they loop, what tools they call, how to sandbox them — see lesson 08A.15; for prompt-craft itself, Module 04; for the security of AI systems, Module 12.
Part 6: Habits that compound#
Deep-dive
Talent gets you started; habits are what separate people who keep improving from people who plateau after the tutorial phase. None of these is exotic — which is exactly why they work.
6.1 A notes/ journal and the TIL log#
Create ~/code/ai-path/notes/ (inside your module-00 workspace) and keep two files:
notes/debug-log.md— the debugging journal from 2.1: what you observed, your hypotheses, what you tried, what happened. Reviewing it weekly teaches you which hypotheses you waste time on and which crack the bug fastest.notes/today-i-learned.md(the TIL log) — one entry per thing you figured out, in your own words, dated. "TIL:git bisect runexits non-zero to mark bad commits" or "TIL:JSONDecodeError: Illegal trailing commameans the JSON has a comma before}". Write it as if explaining to a future you — that is the Feynman technique, and it is the single most effective learning habit there is.
The compounding is real: six months of TIL entries is a personalised reference no course can match, and it is the raw material for learning in public later.
6.2 Read docs and other people's code#
Documentation is not homework — it is the job. Professionals read docs while building, not before. The skill lesson 00.8 teaches applies to every tool: read the quickstart once for orientation, then read the reference section for the specific function you're calling, and the changelog before you upgrade. When docs and behaviour disagree, trust behaviour — and note the discrepancy in your TIL log; docs rot.
Reading other people's code is the same habit applied to source: pick a small, well-regarded open-source project in your language, read one file at a time, and ask "why is it written this way?" The standard library itself is excellent material — it is real, production-grade Python written by experts. You will absorb idioms, error-handling patterns and naming conventions that no tutorial teaches explicitly.
6.3 Build small things every day#
The advice from nearly every experienced engineer is the same: build, don't just consume. Watching tutorials feels like learning and isn't — recognition is not recall, and recall is not production. The fix is a cadence of small, finished artefacts:
- A script that does one annoying task for you (rename files, summarise logs, convert a CSV).
- A tiny CLI with
argparsethat does one thing well. - A single-file program that reads a file and prints a report.
Small enough to finish in an evening, real enough to use tomorrow. The ai-path projects in this module (the tickets.db database, the shell toolkit) are deliberately sized this way. Finish things — a half-built project teaches less than three completed tiny ones, because finishing is where deployment, debugging and documentation habits form.
6.4 Review your own diffs, spaced repetition, learning in public#
Three smaller habits round out the set:
- Review your own diffs before committing.
git diffbeforegit commitis a 30-second habit that catches debug prints, stray files, commented-out code and accidental secrets. It is also the cheapest code review you will ever get. - Spaced repetition. Revisit material just before you'd forget it — the TIL log's dated entries make this natural; revisit a month's-old entry and check you still understand it. Cramming feels productive and evaporates; spaced contact is what moves knowledge to long-term memory.
- Learn in public. Write a short blog post or GitHub gist explaining something you just figured out; contribute a docs fix to an open-source project; answer one Stack Overflow question. Teaching is the strongest test of understanding, and public artefacts become portfolio evidence (Module 14B leans on this heavily).
6.5 Energy, imposter syndrome and interviews#
Learning this much material is a marathon, and a few human factors deserve honest treatment:
- Imposter syndrome — the feeling that everyone else understands and you don't — is near-universal and almost always wrong. The correct response is not to feel better but to verify: run the code, check the docs, ask a precise question. Evidence beats feelings.
- Energy management beats time management for most learners: short daily sessions outperform weekend binges because consolidation happens between sessions. If you're stuck for more than ~45 minutes on the same error, that's a signal to switch tasks or sleep on it — 2.6's flaky-bug insight applies to your own brain too.
- Interview preparation is its own discipline — system-design rounds, coding rounds, "explain what you built" — and Module 14B covers it. The groundwork is what you're doing now: the habits that make you actually good at the work are the same ones that make you appear good in an interview.
Part 7: A plan for this path#
7.1 The module map and honest effort estimates#
Here is the whole path at a glance, with realistic weekly effort estimates. These are estimates, not promises — they assume roughly 5–8 focused hours per week and depend heavily on your prior experience, how much you build versus read, and whether you do the projects. Freshers should expect the longer end; experienced developers switching stacks can often skim.
| Module | Title | Fresher estimate | Switcher estimate | Notes |
|---|---|---|---|---|
| 00 | Developer Foundations | 3–5 weeks | 0–1 week (skip if you know it) | You're here; the machine, terminal, git, HTTP, SQL, docs |
| 01A | Python Essentials | 6–10 weeks | 1–3 weeks (skim to the gaps) | The language itself; the side-by-side lesson helps switchers |
| 01B | Python for AI Engineering | 5–8 weeks | 3–5 weeks | uv, async, httpx, Pydantic, FastAPI, pytest — the toolkit |
| 02 | How LLMs Work | 3–4 weeks | 2–3 weeks | Tokens, embeddings, attention, training — the mental model |
| 03 | LLM APIs Across Providers | 4–6 weeks | 3–4 weeks | Calling OpenAI/Claude/Gemini/OpenRouter properly |
| 04 | Prompt & Context Engineering | 3–4 weeks | 2–3 weeks | The highest-leverage module for product quality |
| 05 | Data Engineering for AI | 4–6 weeks | 3–4 weeks | Parsing, cleaning, ingesting the data RAG needs |
| 06 | Embeddings & Vector Search | 3–4 weeks | 2–3 weeks | Embeddings, similarity, vector indexes |
| 07 | Retrieval-Augmented Generation (RAG) | 4–6 weeks | 3–4 weeks | Retrieval-augmented generation, end to end |
| 08 | Tool Use & Agents | 4–6 weeks | 3–4 weeks | Tool calling, agent loops, MCP, coding agents |
| 09 | Voice & Multimodal Apps | 3–5 weeks | 2–4 weeks | Speech, images, video, realtime |
| 10 | Evaluation | 4–6 weeks | 3–4 weeks | The module that separates prototypes from products |
| 11 | Production & LLMOps | 5–8 weeks | 4–6 weeks | Observability, cost, reliability, deployment |
| 12 | Safety & Security | 3–5 weeks | 2–3 weeks | Threat modelling, injection, privacy, secrets |
| 13 | AI Product Engineering & Capstone | 4–8 weeks | 4–8 weeks | The portfolio product; time varies with scope |
| 14 | Career & Portfolio | 2–4 weeks | 2–4 weeks | CV, GitHub, interviews, negotiation |
Adding up the table's own ranges, a fresher doing every module at a steady 5–8 hours a week is looking at roughly 60–95 weeks, or about 14 to 22 months; a switcher who skims the early modules and moves briskly lands nearer 39–63 weeks. (The sums are just the column totals — your pace, prior experience and how much you build decide where in the range you land, and many learners deliberately stop after Module 11C or 12 for a first job-ready stack, then return for the capstone.) The biggest variable is not intelligence — it is hours of deliberate practice with feedback, which is what the projects and exercises provide.
7.2 How to use each module#
Every module folder in docs/source/ has the same shape:
index.md— who it's for, prerequisites, a "Skip if you already know" box, learning goals, topics, and Fresher/Going-deeper notes. Read the index first; it tells you whether to read fully, skim or skip.- The lesson files — the content, in order. Each ends with exercises; do them. Reading without doing is the tutorial trap from 6.3.
projects.md— starter (guided) and stretch (open-ended) projects. The starters are the spine of the path: they produce the portfolio pieces Module 14B needs.glossary.md— every term, one-line definitions, collected atdocs/source/glossary.md. Look up unfamiliar terms there rather than guessing.
7.3 Self-assessment: where do you start?#
Answer honestly — the point is to place yourself, not to look good. For each module below, score your honest ability before starting it:
Module 00 (Developer Foundations):
| Question | Score 0–2 (0 = never, 1 = a little, 2 = comfortable) |
|---|---|
| I can navigate a terminal, create/move/rename files, and redirect output | |
| I can use git to commit, branch, merge and resolve a conflict | |
| I can push to GitHub and open a pull request | |
| I can explain what happens when a browser requests a URL | |
I can write a basic SQL SELECT with WHERE and JOIN |
|
| I can read API documentation and make an HTTP request by hand |
- Sum 9–12: skip Module 00 entirely (or skim 00.9 only, for the AI-assistant and debugging parts).
- Sum 5–8: skim the lessons you score 2 on; read the rest.
- Sum 0–4: work through all of Module 00 — it is designed for exactly your starting point.
Module 01A (Python Essentials):
| Question | Score 0–2 |
|---|---|
| I can write a Python function with loops, conditions and error handling | |
| I can use lists, dicts, sets and comprehensions fluently | |
I can read and write files, parse JSON, use pathlib |
|
I can define a class and use dataclasses |
|
I can use try/except and read a traceback |
|
| I understand type hints and can read them |
- Sum 9–12: skip 01A (take the index's skip test seriously); go to 01B.
- Sum 5–8: read the lessons where you scored 0–1; skim the rest.
- Sum 0–4: start at 01A.1 and go in order — the module is built for freshers.
Module 01B (Python for AI Engineering):
| Question | Score 0–2 |
|---|---|
I can create a uv project, add dependencies and run scripts in it |
|
I understand environment variables, .env files and os.environ |
|
I can write async/await code and reason about the event loop |
|
I can make an HTTP request with httpx and handle timeouts |
|
| I can define a Pydantic model and validate data with it | |
I can write and run pytest tests, including async tests |
- Sum 9–12: you may be able to skim 01B — but do the projects anyway; they're the portfolio.
- Sum 5–8: read 01B fully; it's the toolkit every later module assumes — skim only the lessons where you scored 2.
- Sum 0–4: start at 01B.1 — no shame, this is the module most people underestimate.
7.4 When you're stuck#
The escalation order from 4.5 applies to the path itself:
- Re-read the lesson's "Fresher note" and the glossary — the term you don't know is usually defined there.
- Run the example — half of "I don't understand" is "I haven't run it".
- Do the exercise — exercises are where understanding converts to skill.
- Ask the assistant as a tutor (5.3) — "explain X as if I'm new" beats "tell me the answer".
- Ask a human — a study group, a forum, a mentor. The AI-engineering community is large and friendly to beginners who ask well-formed questions.
- Come back tomorrow — 6.5 applies: stuck-today is often obvious-next-week.
Part 8: Professional basics#
Reference
8.1 Async communication that gets answers#
Most software communication is written and asynchronous — chat messages, issue comments, PR reviews, emails — because teams span time zones and calendars. The skill is writing messages that get answered without a follow-up meeting:
- Lead with the ask. "Can you review PR #42?" beats three paragraphs of context before the request. State what you need, then give the context.
- Give enough context to act. A good message has: what you're trying to do, what you tried, what happened, what you need (a decision, a review, information). This is the MRE discipline of 4.4 applied to people.
- Write for the reader who has none of your context. They'll read it in a week when you've forgotten you wrote it.
- Use threads and links. Reply in-thread; link the issue, the PR, the log line. "See the error above" is not a link.
- Batch small questions. Five one-line questions in one message beats five interruptions.
8.2 Time, scope and saying no#
Estimates are guesses with error bars, and the professional skill is communicating the uncertainty:
- Give ranges and assumptions. "Two to three days, assuming the API behaves as documented — I'll know more after I spike it" beats a false-precise "Tuesday".
- Say when you're blocked early. A blocker reported on day one costs an hour; reported on day four costs a sprint. "I'm stuck on X, tried A and B, need Y" on day one is a professional move, not a weakness.
- Scope creep is a conversation, not a silent expansion. When asked for more than was estimated, say "that's another day — want me to do it, or defer it?" The conversation is the job; silently absorbing scope is how projects die.
- "No" is a complete sentence. You can't do everything; saying so clearly with reasoning is more useful than a missed deadline.
8.3 Security, privacy and ethics responsibilities#
Every engineer is a security and privacy stakeholder, not just the security team:
- Never commit secrets — keys, tokens, passwords, connection strings. They live in environment variables and secret managers, never in source (00.3 covers
.gitignore; 03.1 Part 3 covers the full key-handling discipline; 12.7 is the security deep-dive). - Treat user data as yours to protect. Personal data has legal weight (GDPR and kin); collect the minimum, store it safely, delete it when done, and never paste it into tools that shouldn't see it (12.4).
- Using other people's code and data has rules. Licences (MIT, Apache, GPL, "no licence") govern what you may do; personal data in datasets has its own rules. Read the licence before you copy; when in doubt, write it yourself or ask.
- Accessibility is a baseline, not a bonus. If you build anything with a UI, it should work with keyboard navigation, screen readers and sufficient contrast. It's both an ethical default and, in many jurisdictions, a legal requirement.
8.4 The professional baseline#
Strip away the tooling and the job is: build things that work, tell people honestly what state they're in, and leave the codebase better than you found it. Small commits, honest estimates, written-down decisions, tests for the things that matter, and a notes/ habit that makes you faster every month — that is what "working like an engineer" means.
Failure gallery#
The failure modes this lesson is really about — what they look like, why they happen, and the first move that gets you unstuck:
| What it looks like | Likely cause | First move |
|---|---|---|
| You changed three things, the bug vanished, and you don't know which change fixed it | Several variables changed at once — the classic debugging failure (2.1) | Revert all but one (git diff, git restore), re-apply them one at a time |
git bisect names a "first bad commit" whose diff looks innocent |
First-bad ≠ root cause; an earlier commit set up the interaction (2.4) | Read the first-bad diff and what it interacts with; check git log around it |
| A test passes alone but fails in the suite — and everyone calls it "just flaky" | Shared state, order dependence, unseeded randomness, time/date assumptions (2.6) | Run the suspect pair together; check the flaky-causes table before ignoring it |
| The assistant's code looks perfect and fails on your first real input | Hallucinated API, outdated version, or an edge case it never considered (5.2) | Read every line, run it, test the edges, check the docs — in that order |
| Your question gets ignored or gets "have you tried turning it off and on" | No minimal reproducible example, no versions, no "what I tried" (4.3, 4.4) | Rewrite with the template: environment, expected vs actual, MRE, attempts |
| The estimate you gave comes in late | The estimate was treated as a promise; scope and assumptions were never stated (8.2) | Give ranges with assumptions; report blockers on day one, not day four |
| The bug only happens "sometimes" and you can't debug what you can't reproduce | Flaky bug — timing, state, environment or data, not the happy path (2.2, 2.6) | Make it fail reliably first: loop it, stress it, or add the suspected delay |
| You can't reproduce the bug at all, even though a colleague swears it happens | Environment or data difference, not code (2.5) | Diff the environments side by side: versions, .env, working directory, OS |
| The traceback points deep inside a library and you don't know where to look | You're reading frames in the wrong direction — or stopping at the wrong frame (3.1) | Read bottom-up: last line is the verdict; find the deepest frame that's your code |
pip install reported success but the import still fails |
Wrong environment — the installer and the interpreter disagree (3.2) | Check sys.executable and which python3; activate the venv/project interpreter |
You pasted a .env file or a customer record into a chatbot "just to debug it" |
Secrets and personal data can be retained, logged, used for training or breached — and you can't un-send them (5.4) | Rotate any exposed credential immediately; redact first (sk-..., user_42) or describe the shape instead |
| Weeks of tutorials later you still can't build the thing | Tutorial hell — consumption without production (6.3) | Finish one small artefact today: a script, a CLI, a single-file report |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Good engineers don't make mistakes, so I shouldn't either." | Everyone makes mistakes; professionals make them visible (tests, small commits, honest reports) and cheap (caught early, easy to undo). |
| "Debugging is just trying things until it works." | That's the anti-pattern. Debugging is a method: observe, hypothesise, experiment one variable, conclude — and write down what you tried. |
| "The last line of the error is all that matters." | It's the verdict, but the frames above it are the journey. Reading only the last line misses where and why. |
| "If I can't reproduce it, it isn't a real bug." | It is real — it's telling you the bug lives in the environment, timing or data, not the happy path. That narrows the search enormously. |
| "Stack Overflow has the answer, so I don't need to understand it." | The highest-voted answer may be outdated or wrong for your version. Read dates, versions and comments; verify before trusting. |
| "AI assistants will replace the need to learn." | They replace the need to memorise, not to understand. You still have to read, test and debug everything they produce — which is the job. |
| "Asking for help means I'm not good enough." | Asking well is a professional skill. The failure mode is asking badly (no context, no attempt) — not asking at all. |
| "I need to learn everything before I start building." | You learn by building. The path's projects are designed so each one teaches the next skill you need. |
| "More hours = faster learning." | Deliberate practice with feedback beats passive hours. A focused hour with a project teaches more than a weekend of tutorials. |
| "If the AI wrote it, it must be fine." | Generated code is plausible, not verified. It hallucinates APIs, misses edge cases and can be insecure — run it, read it, test it, check the docs. |
Key takeaways#
- Software is built by teams. Tickets, branches, pull requests, reviews, standups and estimates are how work is coordinated; "done" means tested and reviewed, not just "ran once".
- Debugging is a method, not a mood. Observe → hypothesise → experiment (one variable) → conclude → verify. Reproduce first, minimise the case, write down what you tried — and experiment freely, because git makes every probe cheap to undo.
- A debugger complements prints:
breakpoint()orpython3 -m pdb script.pylets younext/stepthrough code,pvalues and read the call stack withwhere; prints answer "what is this value?", the debugger answers "how did we get here?". git bisectfinds the culprit commit in O(log n) when a regression appears; alwaysgit bisect resetafterwards.- "What changed?" is the first question: code (
git diff,git log), environment (versions,.env, cwd), or data. - Flaky bugs have known causes — timing, shared state, unseeded randomness, time/date assumptions, external dependencies, order dependence, leftover state. Make them fail reliably before debugging.
- Read tracebacks bottom-up: last line = verdict, frames = journey, deepest your-code frame = where to look.
- The first-errors catalogue (command not found, permission denied, ModuleNotFoundError, indentation, KeyError, IndexError, TypeError, AttributeError, FileNotFoundError, JSONDecodeError, address-in-use, HTTP 401/403/404/429) covers most beginner failures — learn the shape of each.
- Search like a professional: exact error in quotes, tool + version, official docs first, then community; read Stack Overflow dates and versions critically.
- The minimal reproducible example is the key artefact for asking for help — minimal, complete, verifiable.
- AI assistants are tutors and first-draft generators, not oracles: read every line, run it, test the edges, check the docs and versions, check licences — and never paste secrets or private data.
- Habits compound: a
notes/journal and TIL log, daily small builds, reading docs and code, reviewing your own diffs, spaced repetition, learning in public. - The whole path is roughly 14–22 months of part-time study for a fresher (the sum of the module estimates), less for a switcher; use the index's skip tests and the self-assessment to place yourself.
- Professional basics: async communication that gets answers, honest estimates, security/privacy as everyone's job, licences and accessibility as defaults.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Ticket / issue | A unit of work — a bug report, feature request or chore — tracked in a system like GitHub Issues |
| Pull request (PR) | A request to merge a branch into the main codebase, with review built in |
| Code review | A colleague reading your diff and leaving comments before it merges |
| Standup | A short daily sync: what I did, what I'm doing, what's blocking me |
| Estimate | A guess at how long a ticket takes, with uncertainty attached |
| Sprint | A fixed planning window (often 1–2 weeks) in iterative teams |
| "Done" | The professional bar: tested, reviewed, documented — not just "ran once" |
| Debugging | The systematic search for a bug's cause: observe, hypothesise, experiment, conclude |
| Reproduce (a bug) | Making the failure happen reliably on demand |
| Minimise (a case) | Shrinking the input/code to the smallest version that still triggers the bug |
| Minimal reproducible example (MRE/MCVE) | The smallest complete code+input that shows the problem to someone else |
| Bisect | Binary-searching history (or code) to find the first "bad" point; git bisect automates it for commits |
| Flaky bug | A bug that fails intermittently — usually timing, state, randomness or environment |
| Traceback / stack trace | The list of function calls that led to an error, printed when a program crashes |
| Print debugging | Adding temporary print()/logging probes to observe values during a run |
| Debugger | A tool (pdb, VS Code debugger) that pauses execution and inspects live state |
pdb / breakpoint() |
Python's built-in debugger and the call that drops you into it at that line; commands include next, step, continue, p expr, where |
| Post-mortem debugging | Opening the debugger at the point an uncaught exception crashed the program (python3 -m pdb script.py) |
| Rubber-duck debugging | Explaining your problem aloud (to a duck or a person) until the answer surfaces |
| Stack Overflow | A Q&A site where debugging answers are voted on; read dates and versions critically |
| GitHub issue / Discussion | The project's own tracker/forum — where maintainers answer |
| AI coding assistant | A tool (Copilot, Cursor, Claude, ChatGPT) that generates or explains code; verify before trusting |
| Hallucination | Plausible-but-wrong output — invented APIs, outdated versions, subtle bugs |
| Verify-before-trust routine | Read → run → test edges → check docs/versions → check licence, before using generated code |
| TIL log | "Today I learned" journal — dated notes on things you figured out |
| Spaced repetition | Revisiting material just before you'd forget it, to move it to long-term memory |
| Learning in public | Writing/blogging/gisting what you learn; teaching as the strongest test of understanding |
| Imposter syndrome | The unfounded feeling that everyone else understands and you don't |
| Async communication | Written, threaded communication that respects focus time and creates a record |
| Scope creep | Work expanding beyond the original estimate without an explicit conversation |
| Accessibility | Building for keyboard, screen-reader and contrast needs as a baseline, not a bonus |
All terms are also collected in the glossary.
Exercises#
Do these in order; they build on each other. Use a scratch folder inside ~/code/ai-path/.
-
Read a traceback (3.1). Save
buggy_report.pyandtickets.txtfrom 3.1 into a scratch folder and runpython3 buggy_report.py. Without editing the script, write down: the exception type, the function where it failed, and whysplit("|")produced 3 values.Solution
text ValueError: not enough values to unpack (expected 4, got 3) Failed in load_tickets() at the line unpacking the split into 4 names. The last row "T-104|umbrella|feature request" has only 3 "|" fields — no priority — so split("|") returns a 3-item list, and unpacking into 4 names fails. -
Fix it properly (2.2–2.3). Modify
load_ticketsinbuggy_report.pyto skip malformed lines with a printed warning instead of crashing — thefixed_report.pyversion shown at the end of 3.1 is the target pattern. Run it and confirm the good rows still print.Solution
The complete change to
load_tickets(everything else in the file stays the same):python parts = line.strip().split("|") if len(parts) != 4: print(f"skipping malformed line: {line.strip()!r}") continue ticket_id, customer, subject, priority = partsOutput skipping malformed line: 'T-104|umbrella|feature request' T-103 score=4 site down T-101 score=3 cannot log in T-102 score=2 invoice questionThe warning prints while the file is being loaded, before any report line. The three valid rows then print ranked by priority score, highest first — urgent (4), high (3), normal (2) — which is why the order isn't the file order.
T-104never reaches the report because it was skipped. -
First-errors matching (3.2). For each of these, name the error and the first thing you'd check: (a)
zsh: foo: command not found; (b)ModuleNotFoundError: No module named 'pandas'when you "just installed it"; (c)IndentationError: unexpected indent; (d)KeyError: 'total'on a dict that has'sum'; (e)json.decoder.JSONDecodeError: Expecting valuewhen parsing an API response; (f)OSError: [Errno 48] Address already in use.Solution
(a) command not found →
which foo/ typo / not installed / not on PATH. (b) ModuleNotFoundError → wrong environment/venv; checksys.executableandwhich python3. (c) IndentationError → whitespace inconsistent (tabs vs spaces, or a stray indent); the caret points near it. (d) KeyError → the dict has'sum'not'total'; check key spelling/case, or use.get(). (e) JSONDecodeError → the response isn't JSON — probably an HTML error page (401/404); print the first chars. (f) Address already in use → another process holds the port;lsof -i :<port>to find it. -
Print-debug the invoice bug (2.3). Using
invoice.pyfrom the lesson, addprint()probes to confirm which hypothesis (discount-as-number vs tax vs rounding) is correct before fixing it. Then apply the one-line fix and verifyline_total(10.0, 2, 10)returns21.6.Solution
Probes showed
discounted=10.0— the code subtracted the percent (10) from the subtotal (20) instead of subtracting 10% of it. Fix:discounted = subtotal * (1 - discount_pct / 100). Output:21.6. -
git bisectby hand (2.4). In a scratch repo, create 8 commits where a bug is introduced at commit 5 (e.g. change a multiplier). Usegit bisect start/bad/goodmanually (orgit bisect runwith a check script) to find the first bad commit, thengit bisect reset. Paste your session.Solution
One worked version: the script below builds 8 commits of a
calc.pyprice calculator where commit 5 (c5: bulk discount tier) introduces abulk=10default argument — every earlier commit printstotal= 24.0, every later onetotal= 240.0, so "good" vs "bad" is unambiguous. Dates and identity are pinned for the same reason as in 2.4: it makes the transcript below reproducible — your own repos need none of that ceremony.bash # bisect-exercise.sh — 8 commits; the bug lands at commit 5 set -e export GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null TZ=UTC export GIT_AUTHOR_NAME="Learner" GIT_AUTHOR_EMAIL="learner@example.com" export GIT_COMMITTER_NAME="Learner" GIT_COMMITTER_EMAIL="learner@example.com" git init -b main -q . commit() { # $1 = message, $2 = date; new calc.py content on stdin cat > calc.py git add calc.py GIT_AUTHOR_DATE="$2" GIT_COMMITTER_DATE="$2" git commit -qm "$1" } commit "c1: first version" "2026-02-01T10:00:00+00:00" <<'EOF' print("total=", 10 * 2 * 1.2) EOF commit "c2: name the inputs" "2026-02-02T10:00:00+00:00" <<'EOF' PRICE = 10 QTY = 2 TAX = 0.2 print("total=", PRICE * QTY * (1 + TAX)) EOF commit "c3: extract a function" "2026-02-03T10:00:00+00:00" <<'EOF' def total(price, qty, tax): return price * qty * (1 + tax) print("total=", total(10, 2, 0.2)) EOF commit "c4: round to cents" "2026-02-04T10:00:00+00:00" <<'EOF' def total(price, qty, tax): return round(price * qty * (1 + tax), 2) print("total=", total(10, 2, 0.2)) EOF commit "c5: bulk discount tier" "2026-02-05T10:00:00+00:00" <<'EOF' def total(price, qty, tax, bulk=10): return round(price * qty * (1 + tax) * bulk, 2) print("total=", total(10, 2, 0.2)) EOF commit "c6: label output" "2026-02-06T10:00:00+00:00" <<'EOF' def total(price, qty, tax, bulk=10): return round(price * qty * (1 + tax) * bulk, 2) print("total=", total(10, 2, 0.2), "(incl. bulk)") EOF commit "c7: currency symbol" "2026-02-07T10:00:00+00:00" <<'EOF' def total(price, qty, tax, bulk=10): return round(price * qty * (1 + tax) * bulk, 2) print("total=$", total(10, 2, 0.2), "(incl. bulk)") EOF commit "c8: done marker" "2026-02-08T10:00:00+00:00" <<'EOF' def total(price, qty, tax, bulk=10): return round(price * qty * (1 + tax) * bulk, 2) print("total=$", total(10, 2, 0.2), "(incl. bulk)") print("done") EOF git log --onelineThen the session — three tests narrowed eight commits to the culprit (real output from the recipe above):
console $ git bisect start status: waiting for both good and bad commits $ git bisect bad # HEAD (c8) prints total=$ 240.0 — wrong status: waiting for good commit(s), bad commit known $ git bisect good 2f43a0a # c1 is known good Bisecting: 3 revisions left to test after this (roughly 2 steps) [93b005a394e323bb5eebbd3e91d2682f16a3a140] c4: round to cents $ python3 calc.py total= 24.0 $ git bisect good Bisecting: 1 revision left to test after this (roughly 1 step) [521a338698809a2c540abfffeb52813150d23c3b] c6: label output $ python3 calc.py total= 240.0 (incl. bulk) $ git bisect bad Bisecting: 0 revisions left to test after this (roughly 0 steps) [3fef825a5d60ae319f7b1467cf2318a70f8bf93b] c5: bulk discount tier $ python3 calc.py total= 240.0 $ git bisect bad 3fef825a5d60ae319f7b1467cf2318a70f8bf93b is the first bad commit commit 3fef825a5d60ae319f7b1467cf2318a70f8bf93b Author: Learner <learner@example.com> Date: Thu Feb 5 10:00:00 2026 +0000 c5: bulk discount tier calc.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) $ git bisect reset Previous HEAD position was 3fef825 c5: bulk discount tier Switched to branch 'main'git bisecttested three of the eight commits (c4 → c6 → c5) and namedc5: bulk discount tier— wherebulk=10quietly became a default argument and every total inflated tenfold. That's the whole method from 2.4: one known-good, one known-bad, judge each checkout,git bisect resetwhen done. -
What changed? (2.5). Your program worked yesterday and fails today with no code changes. List three environment causes and the command you'd run to check each.
Solution
- Python/package version changed →
python3 --version,pip show <pkg>/uv pip list - Working directory or file moved →
pwd,ls <path> - Environment variable or
.envedited →env | sort,cat .env(check it exists and is loaded) - Also: system clock, network, certificate, disk space.
- Python/package version changed →
-
Flaky-bug hunt (2.6). A test passes alone but fails in the full suite. Name three likely causes and the first experiment for each.
Solution
- Shared mutable state (global/class variable set by an earlier test) → run just that pair of tests together.
- Order dependence (test assumes it runs first/last) → run the suite in a different order or isolate the test.
- Time/date/randomness without a seed → check for
datetime.now(),randomwithout seed, or real sleeps.
-
Write a good question (4.4). Take the
ValueError: not enough values to unpackfrom exercise 1 and write a full question post (title, environment, expected vs actual, MRE, what you tried, the question) as if posting to Stack Overflow.Solution
text Title: ValueError: not enough values to unpack (expected 4, got 3) when loading ticket rows Environment: Python 3.13, macOS, no third-party packages Expected: tickets.txt rows load into dicts; rows missing a field are skipped. Actual: ValueError: not enough values to unpack (expected 4, got 3) — the script crashes on the last row. Minimal example: `buggy_report.py` + `tickets.txt` from [3.1](#31-anatomy-of-a-traceback) — 34 + 4 lines, paste both in full. Tried: (1) printing each split line — confirmed the last row has 3 fields; (2) printing len(line.split("|")) for every row — 4, 4, 4, then 3. Question: What's the cleanest way to skip malformed rows instead of crashing? -
Verify-before-trust drill (5.2). An assistant gives you this snippet for "safe" SQL:
cursor.execute(f"SELECT * FROM users WHERE name = '{name}'"). List three things wrong with it and what you'd do instead.Solution
- SQL injection:
nameis interpolated into the query string — a value like'; DROP TABLE users; --executes. Use parameterised queries:cursor.execute("SELECT * FROM users WHERE name = ?", (name,)). - No validation: nothing checks
nameis a string/expected shape. SELECT *: returns all columns including ones you may not need (and shouldn't expose). Select the columns you need. Also: it "works" on happy-path input, which is exactly why generated code needs edge-case testing.
- SQL injection:
-
Create your
notes/system (6.1). Create~/code/ai-path/notes/debug-log.mdandtoday-i-learned.md. Write your first TIL entry about something you figured out in this lesson (e.g. how to read a traceback, or whatgit bisectdoes). Commit both to yourai-pathrepo.Solution
markdown # notes/today-i-learned.md ## 2026-11-06 - TIL: A Python traceback reads bottom-up — last line is the error type+message, the `File`/`line`/`in` frames above show the call path. Find the deepest frame that's *your* code; that's where the bug is. - TIL: `git bisect` finds the first "bad" commit by binary search — give it one known-good and one known-bad commit, test the middle, repeat. Always `git bisect reset` when done. -
Self-assessment (7.3). Take the three self-assessment quizzes in 7.3. Score yourself honestly and write down which modules to skip, skim and study — then adjust your plan in
notes/.Solution
There is no single right answer — the point is honest placement. Example: a fresher who scores 3 on Module 00, 7 on 01A and 4 on 01B should read all of 00, focus 01A on the 0–1-scored lessons, and start 01B at 01B.1. Record the plan in
notes/path-plan.mdand revisit it monthly. -
Professional-basics scenario (8). Your teammate asks you to "quickly add a feature" that you estimate at 3 days, but they say "it's urgent, can you do it by Friday?" Write the reply you'd send — it should give an honest estimate, surface the trade-off, and propose a path.
Solution
text I can look at it, but honest estimate is ~3 days of focused work — Friday is tight unless we cut scope. Options: (a) I do a minimal version by Friday and the rest next week, (b) we pull in help, (c) we move the deadline. What matters most here — the full feature or a working subset? Happy to spike it this afternoon and firm up the estimate.
Where you'll use this in the AI path#
The habits in this lesson are the substrate every later module stands on:
| Skill from this lesson | Where it pays off later |
|---|---|
Debugging method, tracebacks, git bisect |
03.10 Debugging and Testing LLM Code — LLM calls fail in new ways (rate limits, invalid JSON, refusals) and the same loop applies |
| Reading errors, asking for help | 03.8 Errors, Rate Limits, Timeouts and Retries — provider errors are just better-documented versions of the first-errors catalogue |
| Iterating and debugging prompts | 04.9 Iterating, Debugging and Porting Prompts — the scientific loop applied to prompts instead of code |
| Verifying AI output before trusting | 08A.15 Coding and Computer-Use Agents — agents generate code you must review, test and sandbox |
| Never pasting secrets/private data | 12.4 PII, Privacy and Data Leakage and 12.7 Securing Data and the Supply Chain — the formal treatment of what you must protect |
| Logging instead of print-debugging | 01A.8 Errors, Debugging and Logging and 01B.10 Logging, Debugging and Packaging — the production-grade versions of the probes you used here |
| Career and portfolio | Module 14B: Career Appendix — the habits in Part 6 are literally what the portfolio rewards |
Check yourself#
- What's the difference between "done" in a school project and "done" in a professional team?School "done" = ran once on my machine. Professional "done" = tested (including edge cases), reviewed by a teammate, documented, and committed in small verifiable steps.
- What are the four steps of the debugging loop, and why must you change only one thing at a time?Observe → hypothesise → experiment → conclude. One variable at a time, because changing several makes it impossible to know which change fixed (or broke) what.
- A program worked yesterday and fails today with no code changes. What's your first question, and what are three places you look for the answer?"What changed?" — code (
git diff/git log), environment (Python/package versions,.env, working directory, network), or data. - In a Python traceback, which line do you read first and why? Where do you look for the bug?Read the last line first (the verdict: exception type + message), then walk the
File/lineframes to the deepest frame in your code — that's where the bug lives. ModuleNotFoundError: No module named 'pandas'— you "just installed it". What's the most likely cause and how do you check?You're almost certainly in the wrong environment/venv — checksys.executableandwhich python3, and whetherpip/uvinstalled into the interpreter you're actually running.- What's a minimal reproducible example, and why is it the key artefact for getting help?The smallest code+input that reproduces the problem for someone else — minimal (as little code as possible), complete (everything needed, in the question), verifiable (you tested it reproduces). It's the difference between a 2-minute answer and no answer.
- Name three things AI assistants reliably get wrong.Invented APIs (hallucinated functions/params), outdated versions, subtle edge-case bugs, insecure code (injection, secrets in source), licence/provenance problems.
- What's the verify-before-trust routine, in order?Read every line → run it (scratch first) → test edge cases and failure paths → check the docs/versions → check the licence → only then use it and understand why it works.
- Why is pasting a
.envfile into a chatbot dangerous even if the chatbot "just reads it"?The data may be retained, logged, used for training, or exposed in a breach — you can't un-send it. Treat the chat as a public forum with amnesia. - What's the difference between using an AI assistant as a tutor and as a code dispenser — and which builds skill?Tutor = explain, quiz, hint, review — keeps you doing the thinking, builds skill. Dispenser = writes the code for you — produces code you don't understand and can't debug. The tutor builds the engineer; the dispenser builds dependence.
- Name three causes of flaky tests and one experiment for each.Timing/race conditions (run in a loop or under load), shared mutable state (run the pair of tests together), time/date/randomness without a seed (check
datetime.now(), unseededrandom, real sleeps), order dependence, external dependencies, leftover state. - What's
git bisect, and what must you always do when you're finished with it?git bisectbinary-searches commit history to find the first "bad" commit when a regression appears. Always finish withgit bisect resetto return to your branch. - Why is a TIL log more valuable than re-reading the same tutorial?Because writing it as if explaining to a future you forces retrieval and exposes gaps — the Feynman technique — and the dated entries become a personalised reference you'll actually revisit (spaced repetition).
- Your estimate was 3 days and the stakeholder wants it Friday. What do you say?Give an honest estimate with the trade-off: "~3 days focused; Friday is tight unless we cut scope — options are a minimal version by Friday, pulling in help, or moving the deadline. What matters most?"
- In
pdb, what is the difference betweennextandstep, and how do you look at a variable's value?nextruns the current line and steps over any function it calls;stepsteps into the called function.p nameshows a value,whereshows the call stack, andcontinueruns on to the next breakpoint.
Further resources#
- Python Tutorial — Errors and Exceptions — the authoritative explanation of tracebacks and exception handling.
pdb— The Python Debugger — the interactive debugger you'll meet in 01A.8.- Python Logging HOWTO — why
printisn't enough and howloggingworks. - git-bisect documentation and Pro Git: Debugging with Git — the full bisect treatment.
- Stack Overflow: How do I ask a good question? and How to create a Minimal, Reproducible Example — the canonical guides to asking well.
- How To Ask Questions The Smart Way (Eric S. Raymond) — the classic essay on technical questions; older but still sharp.
- GitHub Docs: Pull Requests and Tracking your work with issues — the mechanics of the workflow in Part 1.
- VS Code Debugging documentation — the visual debugger you'll use in 01A.8/01B.10.
- GitHub Copilot — the current state of the AI coding agent landscape (plans and surfaces change; verify before assuming).
← 00.8 — Reading API Documentation | Module 00 overview | Module 01A: Python Essentials →