Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.10 (2 of 2): Finding and fixing bugs

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Be a detective

Imagine a shop app that charges 1000 pounds for a sandwich. The customer is angry. The shop owner is worried. Somebody must find the cause.

Even good programmers write bugs. What makes them good is how fast they find and fix them. They work like a detective: look at the clues, make a guess, test it.

Key words

WordWhat it meansExample
DebugTo find and fix mistakes in code.
BugA mistake in a program.
LocateTo find where in the code the mistake is.
TracebackThe message Python shows when an error stops the program. It names the line.
Print statementA print line added to see the value of a variable.
DebuggerA tool that runs your code step by step.
BreakpointA marker where the debugger pauses the program.
VariableA name that holds a value.
Trace tableA table where you write the value of each variable after each step.
RobustKeeps working, or stops safely, when something unexpected happens.
Syntax errorThe code breaks the rules of Python. The program does not start.a missing colon
Runtime errorThe program starts, then crashes while it runs.dividing by zero
Logic errorThe program runs but gives a wrong answer. There is no message.a total that is 1 too big

The cells students fill in are left blank in this preview.

Run it: read the message

Code: python
total = 10
bonus = 5
print("Pay is", totl + bonus)

# Run it. Python stops and shows a message.
# Which line number does it give? What is the name of the error?

Make a free account to save your work and track your progress.

Read the message from the bottom

The message looks hard, but it helps you. It tells you three things: where, what and why.

Start at the last line. It names the kind of error and says what is wrong. Then look up for the line number.

Parts of a Python error message

PartExampleWhat it tells you
Line numberline 3Where to look first
The code lineprint("Pay is", totl + bonus)The line that failed
Kind of errorNameErrorWhat type of problem it is
Explanationname 'totl' is not definedWhy it failed: a spelling mistake

The cells students fill in are left blank in this preview.

Debugging has two jobs

Locate the error: find where it is. Correct the error: fix it.

Do the jobs in order. Never change code at random. Make one change, then run the program again. If you change five things at once you will not know which one helped.

Put the debugging steps in order

Have a go

Put the debugging steps in order

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Three kinds of error

KindWhat happensExample
Syntax errorThe code breaks the rules of Python. The program does not start.A missing colon after if
Runtime errorThe program starts, then crashes while it runs.Dividing by zero
Logic errorThe program runs but gives a wrong answer. There is no message.Adding 1 too many to a count

The cells students fill in are left blank in this preview.

Quick check: which kind of error?

Have a go

Quick check: which kind of error?

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Ways to locate a bug

Read the error message first. For a wrong answer with no message, try these.

Add print statements to see values. Make a trace table by hand. Use a debugger to run one line at a time. Or test small parts of the program one by one.

Try it: print to see inside

Code: python
def average(numbers):
    total = 0
    for number in numbers:
        total = total + number
        print("number", number, "total", total)
    return total / len(numbers)

print(average([2, 4, 6]))

# The print line shows the total after each step.
# Delete it when you have found the bug.

Make a free account to save your work and track your progress.

What a debugger lets you do

ToolWhat it does
BreakpointPauses the program at a line you choose
StepRuns one line at a time
Watch or variables windowShows the value of each variable now
ContinueRuns on until the next breakpoint

The cells students fill in are left blank in this preview.

Debugging makes code robust

Every bug you fix is one fewer problem for a user. Debugging is how code becomes robust.

Fix the cause, not the symptom. If a total is wrong, do not add a line that patches the answer. Find the line that makes it wrong. Then run all your tests again, in case the fix broke something else.

Match the problem to the technique

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Fix it: the runtime error

Code: python
names = ["Sam", "Aisha", "Tom"]
for i in range(1, len(names) + 1):
    print("Hello", names[i])

# Expected: Hello Sam, Hello Aisha, Hello Tom.
# Read the message. Which index is too big? Fix the range.

Make a free account to save your work and track your progress.

Fix it: the logic error

Code: python
total = 0
for price in [2.5, 3.0, 1.5]:
    total = price
print("Total:", total)

# Expected: Total: 7.0. It prints 1.5. Add a print line inside the loop
# to see the value of total each time. Then fix it.

Make a free account to save your work and track your progress.

Watch: finding and fixing bugs

Press Play on the short film below. It debugs two programs from this lesson, one step at a time. Watch how each bug is located first, and then corrected with one change.

Film: finding and fixing bugs

Finding and fixing bugs

Every scene, as text

  1. Read the message from the bottom. The program sets total to 10 and bonus to 5, then print("Pay is", totl + bonus) stops it. Python prints Traceback (most recent call last):, the file and line 3, that line with ^ marks under totl, and last NameError: name 'totl' is not defined. Did you mean: 'total'? The last line names the kind of error and says why. Above it, the message points to line 3, so look there first: totl is a spelling mistake for total.
  2. Myth (false): this mistake is a syntax error. A syntax error breaks the rules of Python, so the program does not start. Here lines 1 and 2 run first, setting total and bonus, and Python stops only when it reaches line 3. The program started, then crashed while it ran: a runtime error.
  3. Correct the error with one change: totl becomes total. Then run the program again: print("Pay is", total + bonus) prints Pay is 15.
  4. A logic error: the program runs but gives a wrong answer, and there is no message. The loop should add up 2.5, 3.0 and 1.5, and the lesson expects Total: 7.0. It prints Total: 1.5.
  5. Locate it with a print statement. A print line added inside the loop, print("price", price, "total", total), shows the values each time round: price 2.5 total 2.5, price 3.0 total 3.0, price 1.5 total 1.5, then Total: 1.5. The total is always the price, so total = price replaces the total each time instead of adding to it.
  6. The cure: fix the cause, not the symptom. The line total = total + price adds each price to the total. With the print line deleted, the program prints Total: 7.0. Then run all the tests again, in case the fix broke something else.

Your turn: four bugs

Four functions each have a bug. Read the comments, find the cause and fix it.

  1. average should divide by the right count.
  2. longest_word should give back the longest word.
  3. count_vowels should count capital letters too.
  4. is_leap_year is missing one rule. year % 4 == 0 asks if a year is divisible by 4.

Fix one function, then press Run Tests. Then do the next one.

Code: python
def average(numbers):
    # Give back the average of the numbers. This has a bug. Find it and fix it.
    total = 0
    for number in numbers:
        total = total + number
    return total / (len(numbers) + 1)


def longest_word(words):
    # Give back the longest word in the list. This has a bug. Find it and fix it.
    longest = ""
    for word in words:
        if len(word) < len(longest):
            longest = word
    return longest


def count_vowels(text):
    # Count the vowels a, e, i, o, u in the text, capital letters too.
    # This has a bug. Find it and fix it.
    count = 0
    for letter in text:
        if letter in "aeiou":
            count = count + 1
    return count


def is_leap_year(year):
    # A leap year is divisible by 4, except years divisible by 100,
    # unless they are also divisible by 400. So 2024 and 2000 are leap years, 1900 is not.
    # This has a bug. Find it and fix it.
    if year % 4 == 0 and year % 100 != 0:
        return True
    return False

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.