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
| Word | What it means | Example |
|---|---|---|
| Debug | To find and fix mistakes in code. | |
| Bug | A mistake in a program. | |
| Locate | To find where in the code the mistake is. | |
| Traceback | The message Python shows when an error stops the program. It names the line. | |
| Print statement | A print line added to see the value of a variable. | |
| Debugger | A tool that runs your code step by step. | |
| Breakpoint | A marker where the debugger pauses the program. | |
| Variable | A name that holds a value. | |
| Trace table | A table where you write the value of each variable after each step. | |
| Robust | Keeps working, or stops safely, when something unexpected happens. | |
| Syntax error | The code breaks the rules of Python. The program does not start. | a missing colon |
| Runtime error | The program starts, then crashes while it runs. | dividing by zero |
| Logic error | The 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
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
| Part | Example | What it tells you |
|---|---|---|
| Line number | line 3 | Where to look first |
| The code line | print("Pay is", totl + bonus) | The line that failed |
| Kind of error | NameError | What type of problem it is |
| Explanation | name 'totl' is not defined | Why 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 questionsThree kinds of error
| Kind | What happens | Example |
|---|---|---|
| Syntax error | The code breaks the rules of Python. The program does not start. | A missing colon after if |
| Runtime error | The program starts, then crashes while it runs. | Dividing by zero |
| Logic error | The 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 questionsWays 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
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
| Tool | What it does |
|---|---|
| Breakpoint | Pauses the program at a line you choose |
| Step | Runs one line at a time |
| Watch or variables window | Shows the value of each variable now |
| Continue | Runs 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
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
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
- 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.
- 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.
- Correct the error with one change: totl becomes total. Then run the program again: print("Pay is", total + bonus) prints Pay is 15.
- 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.
- 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.
- 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.
averageshould divide by the right count.longest_wordshould give back the longest word.count_vowelsshould count capital letters too.is_leap_yearis missing one rule.year % 4 == 0asks if a year is divisible by 4.
Fix one function, then press Run Tests. Then do the next one.
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