Coding Hub  /  Practice

debugging drills

Eight broken programs. Each has exactly one bug. Find it by reading and tracing before you open the answer — that is the skill being practised.

How to use these

Copy each program into a file, run it, and read what happens before you change anything.

00 The method

Every drill below has exactly one bug. Four of them crash and four produce a wrong answer without any error at all — those are the harder ones, and the more realistic.

Work in this order every time:

  • Run it. Read the error, or the wrong output, before touching anything.
  • Predict. Say out loud what you think each line does.
  • Trace. For a loop, write down the variables after each pass.
  • Then change one thing and run again.

Changing several things at once is how a one-bug program becomes a three-bug program. One change, one run.

These four crash

Read the traceback; it names the line.

01 The age checker

Asks for an age and says whether the person can vote.

What happens: TypeError: '>=' not supported between instances of 'str' and 'int'

broken.py
age = input("How old are you? ")

if age >= 18:
    print("You can vote")
else:
    print("Not yet")
Show the bug

input() always returns a string, and a string cannot be compared with a number. Convert it.

age = int(input("How old are you? "))

if age >= 18:
    print("You can vote")
else:
    print("Not yet")

02 The last item

Prints every plant in the list, with its position.

What happens: IndexError: list index out of range, after printing three correct lines.

broken.py
plants = ["fern", "cactus", "ivy"]

for i in range(len(plants) + 1):
    print(i, plants[i])
Show the bug

range(len(plants)) already gives 0, 1, 2 — exactly the valid positions. The + 1 adds a fourth pass asking for plants[3], which does not exist.

plants = ["fern", "cactus", "ivy"]

for i in range(len(plants)):
    print(i, plants[i])

# Better still, when you need both:
for i, plant in enumerate(plants):
    print(i, plant)

03 The counter

Counts how many numbers in the list are above 50.

What happens: Prints 1 instead of 4.

broken.py
scores = [72, 55, 91, 68]

for score in scores:
    count = 0
    if score > 50:
        count += 1

print(count)
Show the bug

count = 0 is inside the loop, so it resets on every pass. It belongs above the loop, where it runs once.

scores = [72, 55, 91, 68]

count = 0
for score in scores:
    if score > 50:
        count += 1

print(count)

04 The total

Adds up a shopping list.

What happens: Prints $8.00 — the last price, not the sum.

broken.py
prices = [4.50, 2.25, 8.00]
total = 0

for price in prices:
    total = price

print(f"Total: ${total:.2f}")
Show the bug

total = price replaces the total each pass. To accumulate you need total = total + price, or its shorthand total += price.

prices = [4.50, 2.25, 8.00]
total = 0

for price in prices:
    total += price

print(f"Total: ${total:.2f}")

These four run, and are wrong

No error. Trace them.

05 The grader

Turns a score into a grade.

What happens: Prints Pass for a score of 85, and would print Pass for 95 too.

broken.py
score = 85

if score >= 50:
    print("Pass")
elif score >= 70:
    print("Merit")
elif score >= 90:
    print("Distinction")
Show the bug

The bands are checked lowest first, so everything 50 or above matches the first branch and the rest are never reached. Order the conditions from highest to lowest.

score = 85

if score >= 90:
    print("Distinction")
elif score >= 70:
    print("Merit")
elif score >= 50:
    print("Pass")

06 The average

Averages a list of numbers.

What happens: Gives the right answer here, but gives a wrong one if you add a print inside the loop — and it does four divisions instead of one.

broken.py
numbers = [4, 7, 2, 9]
total = 0

for n in numbers:
    total += n
    average = total / len(numbers)

print(average)
Show the bug

The division is inside the loop, so it is recalculated on every pass using a partial total. It happens to be correct only because the last pass uses the complete total. Move it out.

numbers = [4, 7, 2, 9]
total = 0

for n in numbers:
    total += n

average = total / len(numbers)
print(average)

07 The search

Reports whether a plant is in the list.

What happens: Prints Not found, Found it, Not found — three lines for one question.

broken.py
plants = ["fern", "cactus", "ivy"]
wanted = "cactus"

for plant in plants:
    if plant == wanted:
        print("Found it")
    else:
        print("Not found")
Show the bug

The else runs on every pass that is not a match, so it reports on each item rather than on the search as a whole. Use a flag, or break with a for...else.

plants = ["fern", "cactus", "ivy"]
wanted = "cactus"

found = False
for plant in plants:
    if plant == wanted:
        found = True
        break

if found:
    print("Found it")
else:
    print("Not found")

# Or simply:
if wanted in plants:
    print("Found it")

08 The doubler

Doubles every number in a list.

What happens: Prints [1, 2, 3]. Nothing was doubled.

broken.py
def double_all(numbers):
    for n in numbers:
        n = n * 2

numbers = [1, 2, 3]
double_all(numbers)
print(numbers)
Show the bug

n is a copy of each value, so reassigning it changes only the copy. To change the list you must write back into it by position, or build and return a new list.

def double_all(numbers):
    return [n * 2 for n in numbers]

numbers = [1, 2, 3]
numbers = double_all(numbers)
print(numbers)          # [2, 4, 6]

# Or change it in place by position:
def double_in_place(numbers):
    for i in range(len(numbers)):
        numbers[i] = numbers[i] * 2