Lesson 6 of 6
Reading code like a computer
A computer runs one line at a time and keeps a value for every name. Do the same on paper and you can find bugs without a run button. This lesson covers trace tables, six common bugs, tracebacks, and a four-move debugging loop.
Fill a trace table for a loop: one column per name, one row per pass
Spot the common bugs: an off-by-one range, changing a list while walking it,
==for=,/for//, a missingreturn, and shared rowsRead a traceback from the bottom up and find the line that caused the error, not only the line that broke
Debug with four moves: smallest failing input, predict, trace, first wrong value
Your function returns 8. The answer is 9. You read the code again, and it still looks right. A fourth reading will not help, because you are reading what you meant, not what you wrote.
The computer has no idea what you meant. It runs one line, updates its names, and moves on. To find a bug, do exactly what it does: run the code yourself, one line at a time, and write down every name. On a list of three or four items this takes a minute, and it finds bugs that rereading misses.
In an interview this habit is the test plan. Many coding rounds have no run button, so the only way to check your code is to trace it by hand, out loud. This lesson builds the habit: a trace table on paper, a zoo of common bugs it catches, how to read Python's error messages, and a four-move loop for the bugs you have never seen.
Run it on paper: the trace table
What does the computer keep track of while a simple loop runs? Two things: which line runs next, and the value of every name. A trace table is that on paper: one column per name, one row per pass of the loop.
Here is a loop worth tracing, because its answer is hard to see by reading. It keeps the two biggest order counts, first and second. Before you step through, guess what it prints for [2, 5, 1, 4].
orders = [2, 5, 1, 4]first = 0second = 0for x in orders:if x > first:second = firstfirst = xelif x > second:second = xprint(first, second)
(nothing printed yet)Now the same run as a trace table. Each row is one pass: the item, which test passed, and every name after the pass. The first row is the state before the loop starts.
| Pass | x | Test that passed | first | second |
|---|---|---|---|---|
| before | 0 | 0 | ||
| 1 | 2 | x > first | 2 | 0 |
| 2 | 5 | x > first | 5 | 2 |
| 3 | 1 | neither | 5 | 2 |
| 4 | 4 | x > second | 5 | 4 |
Three rules keep the table honest:
- Write a value only after the line that sets it has run. In pass 2,
second = firstruns beforefirst = x, sosecondgets the old 2, not the new 5. - Write every name on every row, even when it did not change. Then you can check any row on its own.
- Write down which test passed. Many bugs live in a test that went the wrong way.
One row per pass is enough for most loops. When one pass changes several names, as pass 2 does, still work through its lines one at a time, the way the trace does, and write the row when the pass ends.
On paper, fill a trace table for this loop. Use the columns pass, x, x > prev?, ups and prev, and start with a "before" row for the state before the loop. Then type the value of ups after the loop. Reveal one step at a time to check your rows.
nums = [4, 6, 6, 9, 2]
prev = nums[0]
ups = 0
for x in nums:
if x > prev:
ups += 1
prev = xWork it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The next sections are a bug zoo: six common bugs, each shown in a trace so you can watch the first wrong value appear. The sixth, a missing return, also teaches you to read Python's error messages.
Off by one: the walk stops early
Which positions does a loop really visit? range(a, b) gives a, a + 1, and so on up to b - 1. It stops before b, so it gives b - a values (none at all when b is not bigger than a).
An off-by-one bug is a loop or an index that goes one step too far or stops one step short. Off-by-one bugs often come from a + 1 or - 1 copied from a loop where it was right into one where it is wrong.
In a loop that compares each item with the next one, range(len(nums) - 1) is right, because the last item has no next one. Here the same - 1 slipped into a running maximum. Guess what largest([3, 8, 2, 9]) returns before you step through.
def largest(nums):best = nums[0]for i in range(len(nums) - 1):if nums[i] > best:best = nums[i]return best
(nothing printed yet)The fix is to drop the - 1: range(len(nums)). The habit that catches it: for every loop, write down the first and the last value the loop variable takes, and check both against the list. Here the first is 0 and the last is 2, but the last position is 3.
nums has 6 items. How many times does the body of this loop run? Type a whole number.
for i in range(1, len(nums) - 1):
print(nums[i - 1], nums[i], nums[i + 1])Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Changing the list you are walking
This loop is meant to remove every 0 from a list. Predict what it prints before you see it run.
This loop is meant to remove every 0 from the list. Type exactly what it prints. nums.remove(x) deletes the first item equal to x.
nums = [0, 0, 5]
for x in nums:
if x == 0:
nums.remove(x)
print(nums)
Here is the same code, step by step. Watch which item x names on each pass, and what the list looks like when it gets there.
nums = [0, 0, 5]for x in nums:if x == 0:nums.remove(x)print(nums)
(nothing printed yet)A for loop over a list keeps a hidden position: 0, then 1, then 2. No name holds it, so the trace never shows it, but the computer keeps it. Removing an item moves everything after it one place left, so the item that slides into the current position is skipped. Appending has the mirror problem: the walk reaches the new items too, and a loop that appends on every pass never ends.
The fix: never change the list you are walking. Build a new list and return it. (Walking a copy, for x in nums[:], also works, because the copy does not change when nums does.)
Put the lines in order to build without_zeros(nums), which returns a new list holding every item of nums except the zeros, and leaves nums unchanged. Indentation is already part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
kept.append(x)return keptdef without_zeros(nums):nums.remove(x)for x in nums:kept = numsif x != 0:kept = []
One character, a different program
Some bugs are a single character. The first pair is = and ==, and Python catches the mix-up in one direction and runs the other without a word.
= gives a name a value. == asks whether two values are equal. Write = where a test belongs and Python refuses to run the file at all: it raises a SyntaxError, its name for code that breaks the rules of the language. Plain Python points at the line and even suggests the fix (:= is a rarer kind of assignment you will not need here):
File "solution.py", line 2
if x = 3:
^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
The other direction is the dangerous one. == where an assignment belongs is legal Python: the line compares, throws the answer away, and changes nothing. Before you step, guess what this prints.
nums = [4, 1, 6]count = 0for x in nums:if x > 3:count == count + 1print(count)
(nothing printed yet)When a name refuses to change, look for == on the line that should change it.
The second one-character bug is division. / always gives a float (a number with a decimal point), even when the division comes out even: 6 / 2 is 3.0. // divides and rounds down to a whole number: 7 // 2 is 3, because 7 / 2 is 3.5. Rounding down means toward the smaller number, so -7 // 2 is -4, not -3. For positive numbers // matches the "whole part" from lesson 1; for negative numbers it does not, since the whole part of -3.5 would be -3.
Type exactly what this prints, one value per line.
print(9 / 4)
print(9 // 4)
print(8 / 4)
print(-9 // 4)
Each one is a bug in the other's place. / makes a float where Python needs a whole number, such as a list position; the traceback section below shows that error. // where you wanted the exact answer is quieter. Before you step, guess what this average comes out as.
readings = [3, 4]total = 0for x in readings:total += xaverage = total // len(readings)print(average)
(nothing printed yet)When an answer has lost its fraction, look for // where / belongs.
Two rows that are one row
A grid is a list of lists: grid[r][c] is the value in row r, column c. [0] * 3 makes the list [0, 0, 0], so [[0] * 3] * 2 looks like two rows of three zeros. This trace builds that grid, named bad, and a correct one, named good, then changes one cell in each. Predict what each print shows.
bad = [[0] * 3] * 2bad[0][1] = 5good = [[0] * 3 for _ in range(2)]good[0][1] = 5print(bad)print(good)
(nothing printed yet)Why? A box of a list does not hold a copy of its item. It holds a reference: a tag tied to the item, the way a name is tied to its value. [[0] * 3] is a list with one box, tied to one row. * 2 repeats the box, not the row, so both boxes are tied to the same row. It is aliasing (two names for one list, from lesson 1) hiding inside a grid. Repeating the 0 in [0] * 3 is safe, because a number cannot change in place: good[0][1] = 5 ties box 1 of row 0 to a new number and leaves boxes 0 and 2 alone.
Build each row on its own pass. [[0] * 3 for _ in range(2)] is a list comprehension (lesson 5: a loop that builds a list in one line). It runs [0] * 3 once per pass, so it makes two separate rows. (_ is the usual name for a loop variable you never use.)
Which code builds a 3 by 3 board of zeros where board[0][0] = 1 changes only the top-left cell?
Choose one answer, then check.
Reading a traceback from the bottom
When Python cannot go on, it stops and prints a traceback: the chain of calls that led to the error, ending with the error itself. The last bug in the zoo shows how to read one.
Lesson 3 warned about this bug: a function with no return line hands back None, Python's value for "no value". This one builds the right list and never hands it back. Before you step through, guess which line Python will complain about.
def evens(nums):found = []for x in nums:if x % 2 == 0:found.append(x)result = evens([3, 4, 8])print(result[0])
(nothing printed yet)The line that breaks is where Python noticed, not always where you went wrong. Line 7 is fine. The bug is the missing return found at the end of evens.
Outside this lab, Python prints a longer form. Here middle should return the middle item of a list, and it has the / bug from the section on one-character bugs. This is plain Python 3.14 running it, with the file's path shortened to solution.py:
def middle(nums):
mid = len(nums) / 2
return nums[mid]
print(middle([4, 7, 1]))
Traceback (most recent call last):
File "solution.py", line 5, in <module>
print(middle([4, 7, 1]))
~~~~~~^^^^^^^^^^^
File "solution.py", line 3, in middle
return nums[mid]
~~~~^^^^^
TypeError: list indices must be integers or slices, not float
Each line that starts with File, together with the code under it, is a frame: one call that was running when the error happened (the trace draws each one as a box), with the line it had reached. The first frame is the oldest call and the last frame is the newest. Read it from the bottom up:
- The last line names the error and what went wrong: a list index must be a whole number, and this one was a float.
- The frame above it is where it broke: line 3, inside
middle. The~and^marks underline the part of the line that failed,nums[mid]. - Each frame higher up is a caller: line 5 called
middle.<module>means the top level of the file. - Then ask why.
midis 1.5 because line 2 used/. The fix,//, is on line 2, one line above the line the traceback names.
This lab shows the same frames in a shorter form, such as "Line 3 in your code (in middle):", with the error on the last line. Four errors are worth knowing on sight. A dict (dictionary, from lesson 5) appears in one of them: it maps keys to values, so stock = {"apple": 3} maps the key "apple" to 3, and stock["apple"] reads 3.
| Error | Smallest example | What it usually means |
|---|---|---|
IndexError: list index out of range | [4, 7][2] | A position past the end. Check the loop bounds, and any i + 1. |
KeyError: 'kiwi' | stock["kiwi"] | A dict lookup for a key that was never added. |
TypeError: 'NoneType' object is not subscriptable | result[0] when result is None | A value of the wrong type for what the line does. Here a None, often from a missing return. A float position from / is a TypeError too, with the message you saw above. |
NameError: name 'totl' is not defined | total = totl + x | A typo in a name, or a name that was never created. Plain Python, since version 3.10, adds a guess when a close name exists: "Did you mean: 'total'?" |
count_changes should count the neighboring pairs that differ, so count_changes([3, 3, 5]) should be 1. Instead the program stops with the traceback below (file path shortened). Which line holds the bug?
def count_changes(nums):
count = 0
for i in range(len(nums)):
if nums[i] != nums[i + 1]:
count += 1
return count
print(count_changes([3, 3, 5]))
Traceback (most recent call last):
File "solution.py", line 8, in <module>
print(count_changes([3, 3, 5]))
~~~~~~~~~~~~~^^^^^^^^^^^
File "solution.py", line 4, in count_changes
if nums[i] != nums[i + 1]:
~~~~^^^^^^^
IndexError: list index out of range
Choose one answer, then check.
The debugging loop
That completes the zoo: a range that stops early, a list changed mid-walk, == for =, / for //, rows that are one row, and a missing return. Each one showed up as a value that differed from what you expected, sometimes several lines after the mistake.
Here is how to find a bug you have never seen. When a test fails, do not reread and guess. Run four moves:
- Smallest failing input. Shrink the input while it still fails. Fewer items means fewer rows to trace.
- Predict. Before running anything, write down what each name should be on each pass.
- Trace. Step through it, or fill a trace table, next to your prediction.
- Find the first wrong value. The first step where the computer and your prediction disagree points at the bug: the line that just ran, or a line that should have run and did not.
Here is is_sorted, which should return True when no item is bigger than the one after it. Inside, range(len(nums) - 1) is right, because each pass reads nums[i + 1]. But is_sorted([3, 4, 9, 6, 10]) returns True, and 9 is bigger than 6.
Shrink it. Drop the ends: [4, 9, 6] still returns True. Drop the 4 as well: [9, 6] returns False, which is correct, so keep the 4. Three items is the smallest failing input we found.
Predict for [4, 9, 6]: i is 0 (4 and 9 are in order), then 1 (9 and 6 are not), and the function returns False. Now trace it and compare.
def is_sorted(nums):for i in range(len(nums) - 1):if nums[i] > nums[i + 1]:return Falsereturn True
(nothing printed yet)The first surprise is line 5 running while i is still 0. return True is indented inside the loop, so the function answers after checking one pair. Move it out of the loop, level with for, and it runs only after every pair has passed:
def is_sorted(nums):
for i in range(len(nums) - 1):
if nums[i] > nums[i + 1]:
return False
return True
Now is_sorted([4, 9, 6]) checks 4 and 9, then 9 and 6, and returns False.
The debugging loop is itself a walk with a notebook, so it has the four answers this course gives for every algorithm:
Now use the loop on a function with three bugs from the zoo.
average_positive(readings) should return the average of the readings above 0, or 0 when no reading is above 0. For example, average_positive([2, -1, 4]) is (2 + 4) / 2 = 3.0. The code below has three bugs from the zoo. Fix them with the debugging loop, one bug at a time: run the tests and pick a small failing input. [6, -2] is a good one: it should give 6.0, and Watch it run steps through your code on it. Predict i, total and count for each pass, watch it run, and fix the line where the first wrong value appears. Then run the tests again.
Last, practice saying it. The words you write here are the words you will say in the room.
You have written average_positive in an interview. The interviewer asks, "Are you done?" There is no run button. Say what you would do before you answer yes, as you would say it in the room.
Saved in this browser as you type.