unrust

Python debugging exercises: 10 bugs to fix

Published

By the Unrust team · 16 min read · Editorial method

Python debugging exercises: 10 short programs that run but give wrong output. Find the faulty line, fix it and prove it with an assert. Answers included.

What are good Python debugging exercises?

Good Python debugging exercises are short programs that run but misbehave: a wrong value, or a traceback that points at the wrong line. You find the faulty line, explain why it fails, fix it and add an assert that would have caught it. The ten below do that, with output from real runs.

Two of the ten end in a TypeError on a line that is not the cause. The other eight finish normally and print a wrong answer, the harder kind, because nothing tells you to look. None is a syntax-error drill: every program parses and starts. The order runs from the loud bugs to the quiet ones.

Every program was run on CPython 3.11.18, 3.12.16, 3.13.18, 3.14.10 and 3.15.2 on November 18, 2026, and the comments quote what Python printed. The output is identical on all five versions. When a snippet ends in an error, the comment is the last line of the traceback. Each answer ends with asserts, and at least one of them fails on the buggy version, so the proof step was run as well.

The five steps: read, predict, locate, fix, prove

Box about ten minutes per exercise and do steps 1 to 3 with only print() and assert: no debugger, no search, no AI. The steps are a practice-sized version of the loop in the guide to debugging without AI (/guides/debugging-without-ai): make the failure small, test one hypothesis at a time, and finish with a test that would have made the fault obvious.

Each exercise below gives you the program and what it printed, then asks the first question that starts step 2. The 30-second check, the cause, the fix, the asserts and the lesson sit in the collapsed answer under the code. Write your own hypothesis before you open it.

Step       Box    Do this                                           You are done when
---------  -----  ------------------------------------------------  --------------------------------------------
1 Read     1 min  Say what the code should do in one sentence       You can state the output you expected
2 Predict  1 min  Name one cause and the output a check would show  The hypothesis is written down
3 Locate   3 min  Run the cheapest check that could prove it wrong  You can point at one line
4 Fix      2 min  Change the smallest thing that removes the cause  The output matches your sentence from step 1
5 Prove    3 min  Write an assert that fails on the old code        It fails before the fix and passes after it

1. A method returns None: the TypeError points one line too late

podium() should return the three fastest lap times from a list of times in seconds. Instead the program stops with the TypeError in the last comment, and the traceback names the final line of the function.

First question: what does the call on the right of the equals sign hand back? Predict its type, then pick the one-line check that shows it.

def podium(lap_times):
    ranked = lap_times.sort()
    return ranked[:3]

laps = [92.4, 88.1, 90.7, 87.9, 91.3]
print(podium(laps))
# TypeError: 'NoneType' object is not subscriptable
Reveal the answer and explanation

Check: print what sort() returns, then print the list. It returns None, and the list is already in order, because sort() works in place. The Python design FAQ explains the choice: list.sort() sorts the list in place and, to remind you of that, does not return the sorted list, so you are not fooled into overwriting a list you needed to keep unsorted. Here ranked was None from the line above, and the traceback only reports where the None was used.

Fix: sorted() returns a new list and leaves the caller's data alone. The first assert raised TypeError on the old code, and the old call had also reordered laps in place. Lesson: a method that changes an object in place returns None, so never assign its result, and check what a call returns before you build on it.

laps = [92.4, 88.1, 90.7, 87.9, 91.3]

# Check: print what the call returns, then the list itself
print(laps.sort())  # None
print(laps)         # [87.9, 88.1, 90.7, 91.3, 92.4]

# Fix: sorted() returns a new list and leaves the caller's list alone
def podium(lap_times):
    return sorted(lap_times)[:3]

laps = [92.4, 88.1, 90.7, 87.9, 91.3]
print(podium(laps))  # [87.9, 88.1, 90.7]

# Prove it: the old podium() raised TypeError here and had already reordered laps
assert podium(laps) == [87.9, 88.1, 90.7]
assert laps == [92.4, 88.1, 90.7, 87.9, 91.3]

2. A built-in name was overwritten: 'list' object is not callable

This script collects the names of people who scored 4 or more, then builds an ordered list of every name. The first print is correct. The last line fails with the TypeError in the comment, although list() is a built-in that normally just works.

First question: what is the name list bound to when the last line runs? Predict the answer, then pick the one-line check that proves it.

rows = [("ada", 3), ("grace", 5), ("linus", 4)]

list = []
for name, score in rows:
    if score >= 4:
        list.append(name)
print(list)  # ['grace', 'linus']

scores = dict(rows)
ordered = list(scores)
# TypeError: 'list' object is not callable
Reveal the answer and explanation

Check: compare the name with the real built-in. list is builtins.list prints False, and type(list) is <class 'list'>, so the name now refers to a list, not to the type. Python looks a name up in the local scope, then in enclosing functions, then in the module's globals and, last, in the built-ins. The assignment list = [] created a global that is found first, so list(scores) tried to call the list ['grace', 'linus']. del list removes the global and the built-in shows through again.

Fix: give the variable its own name, here high_scorers. The traceback is far from the cause: the error is on the last line and the assignment is at the top. Ruff 0.17.5 flags the assignment as A001 (builtin-variable-shadowing) once the A rules are selected. Lesson: when a built-in is not callable, look for the last assignment to that name in the module, not for a bug in the call.

import builtins

# Check: what is the name list bound to after the assignment in the exercise?
list = []
print(list is builtins.list)  # False
print(type(list))             # <class 'list'>
del list                      # remove the module-level name and the built-in shows through
print(list is builtins.list)  # True

# Fix: give the variable its own name
rows = [("ada", 3), ("grace", 5), ("linus", 4)]
high_scorers = []
for name, score in rows:
    if score >= 4:
        high_scorers.append(name)

ordered = list(dict(rows))
print(ordered)  # ['ada', 'grace', 'linus']

# Prove it: with the old code, list was no longer the built-in
assert list is builtins.list
assert high_scorers == ["grace", "linus"]
assert ordered == ["ada", "grace", "linus"]

3. A default replaces a legal 0: retries=0 is ignored

max_attempts() returns how many times a request may be sent: the first try plus the configured retries, with 3 retries as the default when the setting is missing. A team sets retries to 0 on a payment call that must never be repeated. The program says that call may be sent 4 times.

First question: which values of retries are falsy but legal? Predict what {}, {"retries": None} and {"retries": 0} should each return, then compare.

DEFAULT_RETRIES = 3

def max_attempts(options):
    retries = options.get("retries") or DEFAULT_RETRIES
    return 1 + retries

print(max_attempts({}))                 # 4
print(max_attempts({"retries": 5}))     # 6
print(max_attempts({"retries": 0}))     # 4
Reveal the answer and explanation

Check: call it with the key missing and with 0, and compare. Both print 4, so 0 is being treated as not set. options.get("retries") or DEFAULT_RETRIES returns the second operand whenever the first is false, and 0, 0.0, an empty string, an empty list and None are all false. PEP 8 warns about the same mistake in the form if x when you mean if x is not None.

Fix: test for None, so only a missing or None setting takes the default and an explicit 0 survives. The first assert returned 4 on the old code; the other three already passed. Lesson: x or default asks whether x is truthy, not whether it is missing. JavaScript has the same trap with ||, covered in /blog/javascript-defaults-or-vs-nullish, and pattern 2 of /blog/idiomatic-python-examples covers the same trap from the idiom side.

DEFAULT_RETRIES = 3

# Fix: use the default only when the key is missing or None, not for every falsy value
def max_attempts(options):
    retries = options.get("retries")
    if retries is None:
        retries = DEFAULT_RETRIES
    return 1 + retries

print(max_attempts({"retries": 0}))  # 1

# Prove it: the old code returned 4 for the first assert
assert max_attempts({"retries": 0}) == 1
assert max_attempts({"retries": None}) == 4
assert max_attempts({}) == 4
assert max_attempts({"retries": 5}) == 6

4. A starting value that is not in the data: the best day is 0

best_day() should return the largest change in an account balance over a week. It is right for a mixed week and wrong for a week of losses: the last line prints 0, although no day changed by 0.

First question: could the starting value of best be the answer? Predict what the function returns for an all-negative week and for an empty list, then check both.

def best_day(daily_change):
    best = 0
    for change in daily_change:
        if change > best:
            best = change
    return best

print(best_day([4, -2, 7]))    # 7
print(best_day([-5, -2, -9]))  # 0
Reveal the answer and explanation

Check: run the all-negative week and the empty list. Both return 0. The loop only replaces best when a change is larger than it, and nothing beats 0 in a week of losses, so the seed survives as the answer. A seed of 0 claims that at least one value is 0 or more, and this data breaks the claim.

Fix: max() takes its starting point from the data, and default=None says what an empty week returns; without default, max() raises ValueError on an empty iterable. The all-negative and empty asserts failed on the old code. The mixed-week assert passed before and after, which is why a single happy-path test would not have caught it. Lesson: an accumulator's starting value is a claim about the data. 0 is right for a sum and wrong for a maximum; if you keep the loop, seed best from the first item. The only thing Ruff 0.17.5 says about the loop is a style suggestion to write best = max(best, change), which would keep the bug.

# Fix: a maximum of nothing is None, not 0, and 0 is never a day that happened
def best_day(daily_change):
    return max(daily_change, default=None)

print(best_day([-5, -2, -9]))  # -2
print(best_day([]))            # None

# Prove it: the old code returned 0 for both of the first two inputs
assert best_day([-5, -2, -9]) == -2
assert best_day([]) is None
assert best_day([4, -2, 7]) == 7

5. A list changes while you loop over it: one order is skipped

This batch job should drop every cancelled order from today's batch, leaving 103 and 105. It finishes without an error and prints a list that still contains 102, which was cancelled.

First question: is the list the same length at the start and at the end of each pass? Predict which orders the loop actually looks at, then print the position, the order and the list on each pass.

batch = [101, 102, 103, 104, 105]
cancelled = {101, 102, 104}

for order_id in batch:
    if order_id in cancelled:
        batch.remove(order_id)

print(batch)  # [102, 103, 105]
Reveal the answer and explanation

Check: the trace shows the loop looking at 101, 103 and 104, and never at 102. After 101 is removed, 102 slides into position 0, but the loop moves on to position 1, which now holds 103. When 104 is removed at position 2, three items are left, so the loop ends. The Python tutorial warns that code which modifies a collection while iterating over it can be tricky to get right, and suggests looping over a copy or creating a new collection.

Fix: build a new list with a comprehension. Looping over a copy, for order_id in batch[:], also works, because remove() edits the original while the loop walks the copy. Ruff 0.17.5 reports the original loop as B909 (loop-iterator-mutation) when preview rules are on. Lesson: removing an item shifts the rest down while the loop's position still moves up by one, so one item is stepped over. Do not change the collection you are walking. /blog/trace-table-examples shows how to build a trace table by hand.

batch = [101, 102, 103, 104, 105]
cancelled = {101, 102, 104}

# Check: print the position, the item and the list after each pass
for position, order_id in enumerate(batch):
    if order_id in cancelled:
        batch.remove(order_id)
    print(position, order_id, batch)
# 0 101 [102, 103, 104, 105]
# 1 103 [102, 103, 104, 105]
# 2 104 [102, 103, 105]

# Fix: build a new list instead of editing the one the loop is walking
batch = [101, 102, 103, 104, 105]
batch = [order_id for order_id in batch if order_id not in cancelled]
print(batch)  # [103, 105]

# Prove it: the old loop left 102 in the batch
assert batch == [103, 105]

6. Rows share one list: marking one seat marks them all

A booking script keeps a seating plan as a list of rows and marks a single seat as taken. The printed plan shows seat 1 taken in both rows. Nothing raises an error.

First question: are the rows two separate lists, or one list shown twice? Predict the one-line check that tells them apart.

seats = [["free"] * 3] * 2

seats[0][1] = "taken"
print(seats)  # [['free', 'taken', 'free'], ['free', 'taken', 'free']]
Reveal the answer and explanation

Check: seats[0] is seats[1] prints True, so both rows are one object. Multiplying a list with * repeats references to the same inner list; it does not copy it. The Python Programming FAQ describes exactly this: replicating a list with * only creates references to the existing objects, and changes to one row show in all rows. So seats[0][1] = "taken" wrote into the one list that both rows point at.

Fix: a comprehension that builds a new inner list for each row. The asserts check that the rows are different objects and that the second row is untouched; both failed on the old grid. The inner ["free"] * 3 is safe, because strings cannot be changed in place. Lesson: * on a list of lists repeats references. When two parts of a program change together, check identity with is before anything else.

seats = [["free"] * 3] * 2
print(seats[0] is seats[1])  # True

# Fix: build each row separately
seats = [["free"] * 3 for _ in range(2)]
seats[0][1] = "taken"
print(seats)  # [['free', 'taken', 'free'], ['free', 'free', 'free']]

# Prove it: the old grid failed both of these
assert seats[0] is not seats[1]
assert seats[1] == ["free", "free", "free"]

7. Callbacks use the last loop value: only one tax rate is right

This script builds one price function per tax band and prints the price of 100 in each band. The prices should be 100.0, 105.0 and 120.0. All three print 120.0, and only the last is correct, so checking just the standard band would have passed.

First question: does a lambda look up rate when it is created or when it is called? Predict what the three results do if rate changes after the loop.

RATES = {"zero": 0.0, "reduced": 0.05, "standard": 0.20}

price_with_tax = {}
for band, rate in RATES.items():
    price_with_tax[band] = lambda net: round(net * (1 + rate), 2)

for band in RATES:
    print(band, price_with_tax[band](100))
# zero 120.0
# reduced 120.0
# standard 120.0
Reveal the answer and explanation

Check: define a function that reads a variable, change the variable, then call the function. It sees the new value, because a function looks a name up when it is called. The Python Programming FAQ describes the same trap with squares: x is not local to the lambdas and is accessed when the lambda is called, not when it is defined. After the loop, rate is 0.2, so every band charges the standard rate.

Fix: bind the value when the function is created. functools.partial(add_tax, rate=rate) stores the current rate as an argument; the FAQ's alternative is a default argument, as in lambda net, rate=rate. Ruff 0.17.5 reports the original lambda as B023 (function-uses-loop-variable). The first two asserts failed on the old code and the third passed, which is why the last case is the worst one to test with. Lesson: a function made in a loop captures the variable, not its value at that moment.

from functools import partial

# Check: a lambda reads rate when it is called, not when it is defined
rate = 1
show = lambda: rate
rate = 2
print(show())  # 2

# Fix: bind the value when each function is created
RATES = {"zero": 0.0, "reduced": 0.05, "standard": 0.20}

def add_tax(net, rate):
    return round(net * (1 + rate), 2)

price_with_tax = {band: partial(add_tax, rate=rate) for band, rate in RATES.items()}
for band in RATES:
    print(band, price_with_tax[band](100))
# zero 100.0
# reduced 105.0
# standard 120.0

# Prove it: the old lambdas returned 120.0 for the first two bands
assert price_with_tax["zero"](100) == 100.0
assert price_with_tax["reduced"](100) == 105.0
assert price_with_tax["standard"](100) == 120.0

8. Floats compared with ==: 1.10 + 2.20 is not 3.30

A checkout script compares what the customer paid, 3.30, with the sum of two item prices, 1.10 and 2.20. On paper the amounts are equal. The program prints balance due.

First question: is each side of the == an exact value, or the nearest binary fraction to what you typed? Predict the one-line check that shows what the sum really holds.

paid = 3.30
items = [1.10, 2.20]

total = sum(items)
print(total)  # 3.3000000000000003
if total == paid:
    print("settled")
else:
    print("balance due")  # balance due
Reveal the answer and explanation

Check: print repr() of the sum and a long format of 1.10. Python stores 1.10 as the nearest binary fraction, 1.10000000000000008882 to 20 places, so the sum is 3.3000000000000003 and an exact comparison with 3.30 is False. The decimal module documentation uses the same pair: end users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003.

Fix for money: build Decimal values from strings and compare those; the documentation says decimal is preferred in accounting applications that have strict equality invariants. Decimal(1.10) would copy the float's error, because a float is converted to its exact decimal value, 1.100000000000000088817841970012523233890533447265625. Fix for measurements: compare with math.isclose(), whose default relative tolerance is 1e-09; near zero it needs an abs_tol. Lesson: never use == on floats that were computed. Choose exact decimal arithmetic, or a tolerance you picked on purpose.

import math
from decimal import Decimal

# Check: the repr of the sum, then 20 digits of one stored price
print(repr(1.10 + 2.20))  # 3.3000000000000003
print(f"{1.10:.20f}")     # 1.10000000000000008882

# Fix for money: build Decimals from strings, never from floats
paid = Decimal("3.30")
items = [Decimal("1.10"), Decimal("2.20")]
print(sum(items) == paid)  # True

# Fix for measurements: compare within a tolerance you chose
print(math.isclose(1.10 + 2.20, 3.30, rel_tol=1e-9))  # True

# Prove it: the old exact comparison of floats printed "balance due"
assert sum(items) == paid
assert math.isclose(sum([1.10, 2.20]), 3.30, rel_tol=1e-9)

9. A blanket except hides the bug: the port is always 8080

read_port() should read a port from a JSON config file and fall back to 8080 only when no port is set. The config says 9000. The program prints 8080, with no error and no log line.

First question: which exception did the handler swallow? Predict what you would see if the handler were not there, then run the first line of the try on its own.

import io
import json

def read_port(config_file):
    try:
        settings = json.loads(config_file)
        return int(settings["port"])
    except Exception:
        return 8080

config = io.StringIO('{"port": 9000}')
print(read_port(config))  # 8080
Reveal the answer and explanation

Check: run the first line of the try on its own and print the exception. It is a TypeError: json.loads() takes a string, and the code passed a file object. That is a programming error, not a missing setting, and except Exception turned it into a plausible default on every call. The Python tutorial says Exception can be used as a wildcard, but it is good practice to be as specific as possible and let unexpected exceptions propagate. PEP 8 adds that a try clause should hold the minimum amount of code, because a broad one masks bugs.

Fix: json.load() reads a file object, a missing key falls back through dict.get(), and a bad value such as "abc" now raises ValueError at the line that caused it. The first assert returned 8080 on the old code. Ruff 0.17.5 flags the handler as BLE001 (blind-except). Lesson: a fallback value is a decision about what is acceptable. Catch only the failure you can name, and let the rest crash.

import io
import json

# Check: run the line inside the try and let the exception show itself
try:
    json.loads(io.StringIO('{"port": 9000}'))
except Exception as exc:
    print(type(exc).__name__, exc)
# TypeError the JSON object must be str, bytes or bytearray, not StringIO

# Fix: load() reads a file object, and nothing swallows the other errors
def read_port(config_file, default=8080):
    settings = json.load(config_file)
    return int(settings.get("port", default))

print(read_port(io.StringIO('{"port": 9000}')))  # 9000
try:
    read_port(io.StringIO('{"port": "abc"}'))
except ValueError as exc:
    print(exc)  # invalid literal for int() with base 10: 'abc'

# Prove it: the old code returned 8080 for the first assert
assert read_port(io.StringIO('{"port": 9000}')) == 9000
assert read_port(io.StringIO("{}")) == 8080

10. A loop bound is off by one: binary search misses the last item

find() should return the index of an id in a sorted list, or -1 when the id is absent. Every id in ids is present, so searching for each one should print [0, 1, 2, 3, 4]. It prints -1 for two of them, and it also fails on a list of one item.

First question: is hi inclusive or exclusive, and does the loop condition agree with it? Predict which two ids go missing and what they have in common.

def find(sorted_ids, target):
    lo, hi = 0, len(sorted_ids) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if sorted_ids[mid] == target:
            return mid
        if sorted_ids[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

ids = [3, 8, 15, 21, 40]
print(find(ids, 15))                # 2
print([find(ids, x) for x in ids])  # [0, -1, 2, 3, -1]
print(find([7], 7))                 # -1
Reveal the answer and explanation

Check: follow the window from lo to hi for a missing id. For 40 it shrinks from 0..4 to 3..4 to 4..4, and at lo == hi the condition lo < hi is False, so the loop ends without ever reading ids[4]. For 8 the window goes 0..4, 0..1, 1..1 and ends the same way. hi starts at len(sorted_ids) - 1, the last valid index, so the window includes both ends, and a window of one item still has to be searched. A list of one item starts in that state.

Fix: while lo <= hi. The asserts try every id, a one-item list, an absent id and an empty list; the first two failed on the old code. Lesson: choose inclusive or exclusive bounds first, then make the starting value, the loop condition and both updates agree, and always test empty, one item, first and last. In real code, bisect.bisect_left finds the position and the bisect documentation shows how to turn it into an exact lookup. The same first-check, last-visit habit is in /blog/off-by-one-loop-boundaries.

ids = [3, 8, 15, 21, 40]

# Fix: hi is the last valid index, so the window lo..hi is inclusive and
# a window of one item (lo == hi) must still be searched
def find(sorted_ids, target):
    lo, hi = 0, len(sorted_ids) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if sorted_ids[mid] == target:
            return mid
        if sorted_ids[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

print([find(ids, x) for x in ids])  # [0, 1, 2, 3, 4]
print(find([7], 7), find([], 7))    # 0 -1

# Prove it: the old condition failed the first two asserts
assert [find(ids, x) for x in ids] == [0, 1, 2, 3, 4]
assert find([7], 7) == 0
assert find(ids, 9) == -1
assert find([], 7) == -1

Bug-class index: symptom and 30-second check

Use this table after the exercises, or as a first guess when a real program misbehaves. Each check is a single line you can run.

Mutable default arguments and exhausted iterators are two more classics. They have their own write-up (/blog/python-exhausted-iterators-and-mutable-defaults) and a companion tool (/tools/python-iterator-default-explorer), so they are in the table but are not repeated as exercises.

#   Bug class                    What you see                                   30-second check
--  ---------------------------  ---------------------------------------------  ------------------------------------------
1   Method returns None          TypeError on the line after the call           print(type(result)) right after the call
2   Shadowed built-in            'list' object is not callable                  print(list is builtins.list)
3   Falsy value read as missing  0, "" or [] replaced by the default            call it with 0 and with the key missing
4   Wrong starting value         Right on typical input, wrong on all-negative  call it with [-5, -2, -9] and with []
5   Mutation while looping       An item skipped, no error                      print position, item and list on each pass
6   Shared inner list            Edit one row and every row changes             print(rows[0] is rows[1])
7   Late-bound closure           Every callback uses the last loop value        change the variable, call a callback again
8   Float equality               == is False for values that look equal         print(repr(value))
9   Blanket except               A fallback value on every run                  run the try body without the handler
10  Off-by-one bound             The first or last item is missing              test empty, one item, first and last
-   Mutable default argument     Results of earlier calls show up               print(func.__defaults__) after two calls
-   Exhausted iterator           A second pass sees nothing, or only a suffix   print(iter(x) is x)

Which of these would a linter catch?

Ruff 0.17.5 points at the bug in four of the ten programs when the four rules in the config below are on: A001 for the shadowed list in exercise 2, B909 for the loop that edits its own list in exercise 5 (a preview rule), B023 for the lambda in exercise 7 and BLE001 for the blind except in exercise 9. With preview on, this version prints rule names where it normally prints codes. With every rule selected, preview included, it reported nothing about the bug in the other six.

A rule is a hint, not a proof; the next step is still the five steps above. The other six, exercises 1, 3, 4, 6, 8 and 10, are valid code with the wrong intent, and only a run, a test or a reviewer can show that.

# ruff.toml
[lint]
preview = true
select = ["A001", "B023", "B909", "BLE001"]

$ ruff check --output-format concise ex02.py ex05.py ex07.py ex09.py
ex02.py:3:1: builtin-variable-shadowing: Variable `list` is shadowing a Python builtin
ex05.py:6:9: loop-iterator-mutation: Mutation to loop iterable `batch` during iteration
ex07.py:5:57: function-uses-loop-variable: Function definition does not bind loop variable `rate`
ex09.py:8:12: blind-except: Do not catch blind exception: `Exception`
Found 4 errors.

Practise debugging with the AI off

Reading ten answers is not the same as finding a bug cold. Unrust's free diagnostic samples Debugging as one of six skills, alongside recall, tracing, find the flaw, idiom and AI-slop detection. The Debugging drills ask you to locate the broken line and name the root cause, and the whole diagnostic takes about 14 minutes with the AI off. You can take it in Python.

For untimed practice, Unrust's Python debugging page (/languages/python/debugging) pairs one original example with a three-question checklist and a three-step practice loop, and the guide to debugging without AI (/guides/debugging-without-ai) explains the method behind the five steps. Mutable defaults and exhausted iterators have their own post (/blog/python-exhausted-iterators-and-mutable-defaults) and a companion tool (/tools/python-iterator-default-explorer).

Related reading: the loop-boundary habit behind exercise 10 is in /blog/off-by-one-loop-boundaries, and the loop boundary explorer (/tools/loop-boundary-explorer) lets you try it, although it models a JavaScript loop. To practise predicting output before you run code, see /blog/code-tracing-questions. When the failure is in a service rather than a script, see /blog/trace-first-symptom-vs-root-cause-in-logs.

Python debugging exercises: FAQ

What are good Python debugging exercises for beginners? Start with the two loud ones, a method that returns None and a built-in name you overwrote, because the traceback at least tells you something is wrong. Then try exercises 3 and 4, which run and print a wrong answer but have a one-line cause. Save the float, except and binary search exercises for later.

How do I practice debugging in Python? Work one short buggy program at a time in a ten-minute box: say what it should do, name one cause, run the cheapest check, make the smallest fix, then write an assert that fails on the old code. Keep the debugger, search and AI closed until you have a hypothesis, and keep the asserts as regression tests.

How do you find the bug in Python code without a debugger or AI? Write down the expected output, the actual output and the smallest input that shows the gap. Name one cause, then run the cheapest check that could prove it wrong: print a type, an id or a repr, print the list on each loop pass, or call the function with zero, empty and negative input. Change one thing and rerun.

What are the most common bugs in Python programs? There is no trustworthy ranking, so treat this as a list of classics, not a statistic. The Python documentation itself warns about in-place methods that return None, lists copied by reference, loops that edit what they iterate, late-binding closures, float equality and broad exception handlers. Mutable defaults and exhausted iterators are the other two.

Are there Python debugging exercises with answers? Yes. The ten above each have a collapsed answer with the 30-second check, the cause, the fix, asserts that fail on the old code and the lesson, and every snippet was run on CPython 3.11 to 3.15. Open an answer only after you have written your own hypothesis. Unrust's Python debugging page offers more untimed practice.

References and next steps

Find the broken line against the clock

Take Unrust's free diagnostic in Python with the AI off: about 14 minutes. Debugging is one of six skills it samples, alongside recall, tracing, find the flaw, idiom and AI-slop detection.

More from the blog