LECTURE 2.3

Finding and fixing mistakes

Reading error messages and debugging, step by step

Today's key line of code
print("Total: " + 5)
# TypeError: can only concatenate
# str (not "int") to str

Where we are: Lecture 2, part 3 of 3

Part 3 of 3L2Python basics
L3Decisions and loops
L4Counting words
L5Real data
L6Build the model

Today you will

  1. 1Tell apart syntax, runtime and logic errors
  2. 2Read an error message from the bottom up
  3. 3Recognise the ten errors you will meet most
  4. 4Find logic errors by printing values
  5. 5Follow a debugging routine, and ask for help well
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal2 / 26

Three kinds of mistakes

1

Syntax error

Python cannot read the code: a missing colon, bracket or quote. Nothing in the cell runs.

2

Runtime error

The code starts, then crashes at one line: a wrong name, a wrong type, a missing file.

3

Logic error

No message at all, but the answer is wrong. The hardest kind, because Python is happy.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal3 / 26

Anatomy of an error message

Error message (traceback)
Traceback (most recent call last):
File "shop.py", line 6, in <module>
print("Average: " + average)
~~~~~~~~~~~~^~~~~~~~~
TypeError: can only concatenate str (not "float") to str
Traceback: the path Python took. Read it from the bottom up
Where: file name and line number
The exact line that failed
Markers point at the failing part
Error type: the kind of problem
Message: what went wrong, in words
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal4 / 26

A debugging routine you can always follow

1

Read the last line

Error type and message. Say in your own words what Python is complaining about.

2

Find the line

Go to the line number. Check that line and the one just above it.

3

Make one change

Change one thing only, then run again. Several changes at once hide what fixed it.

4

Still stuck?

Print the values involved, shrink the problem, then ask for help with the full error.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal5 / 26

The errors you will meet most

ErrorUsually meansTypical fix
SyntaxErrorMissing colon, bracket or quoteLook at the marked spot and the line above
IndentationErrorBlock not indented, or mixed spacingIndent the block by 4 spaces
NameErrorName misspelled or never createdCheck spelling; run the cell that creates it
TypeErrorWrong type for the operationConvert: int(), str(), or an f-string
ValueErrorRight type, impossible valueCheck the value: int("ten") cannot work
IndexErrorPosition past the end of a listPositions run from 0 to len - 1
KeyErrorDictionary key does not existUse d.get(key, 0) or check the key
ZeroDivisionErrorDividing by zeroCheck the divisor first, for example empty lists
FileNotFoundErrorFile not where Python looksPut the file next to the notebook
ModuleNotFoundErrorLibrary not installedLab: use Anaconda. Home: pip install
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal6 / 26

Bug hunt 1: find the mistake

Predict first
Code
age = "20"
next_year = age + 1
print(next_year)
?

This cell fails. Which line, and why? Decide before you run it.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal7 / 26

Answer: Bug hunt 1: find the mistake

Code
age = "20"
next_year = age + 1
print(next_year)
Output
TypeError: can only concatenate str (not "int") to str
  • "20" in quotes is text, not a number
  • Text + number is a TypeError
  • Fix: age = 20, or convert with int(age)
  • Data read from files and input() often arrives as text
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal8 / 26

Bug hunt 2: find the mistake

Predict first
Code
scores = [70, 85, 90]
total = 0
for s in scores:
    total = total + s
average = total / len(score)
?

This cell fails. Which line, and why? Decide before you run it.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal9 / 26

Answer: Bug hunt 2: find the mistake

Code
scores = [70, 85, 90]
total = 0
for s in scores:
    total = total + s
average = total / len(score)
Output
NameError: name 'score' is not defined
  • score was never created: the list is scores
  • NameError points to the line with the typo
  • Recent Python versions may add: Did you mean: 'scores'?
  • Fix: len(scores)
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal10 / 26

Bug hunt 3: find the mistake

Predict first
Code
marks = []
average = sum(marks) / len(marks)
print(average)
?

This cell fails. Which line, and why? Decide before you run it.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal11 / 26

Answer: Bug hunt 3: find the mistake

Code
marks = []
average = sum(marks) / len(marks)
print(average)
Output
ZeroDivisionError: division by zero
  • An empty list has length 0
  • Dividing by 0 is impossible: ZeroDivisionError
  • Fix: check first, if len(marks) > 0:
  • Real data often has empty groups
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal12 / 26

Logic error: no message, wrong answer

Predict first
Code
a = 70
b = 90
average = a + b / 2
print(average)
?

Expected average of 70 and 90: 80. What does it print?

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal13 / 26

Answer: Logic error: no message, wrong answer

Code
a = 70
b = 90
average = a + b / 2
print(average)
Output
115.0
  • Division happens before addition
  • So Python computes 70 + 45 = 115.0
  • Fix: (a + b) / 2
  • Always test with a case where you know the answer
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal14 / 26

Find logic errors by printing values

  • Goal: count the vowels in "banana" (expected 3)
  • The loop runs, but the answer is 1
  • Next step: print the values inside the loop
  • Look for the round where the value goes wrong
Code
word = "banana"
count = 0
for ch in word:
    if ch in "aeiou":
        count = 1
print(count)
Output
1
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal15 / 26

Add a print inside the loop

  • Each round now shows ch and count
  • count never goes above 1
  • The line count = 1 sets instead of adds
  • Fix: count = count + 1, then delete the debug print
Code
word = "banana"
count = 0
for ch in word:
    if ch in "aeiou":
        count = 1
    print("ch =", ch, "count =", count)
print(count)
Output
ch = b count = 0
ch = a count = 1
ch = n count = 1
ch = a count = 1
ch = n count = 1
ch = a count = 1
1
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal16 / 26

Watch it run: hunting the logic error

WATCH FOR

  • No error message, but the answer is 1
  • Watch count in Memory after each vowel
  • It never goes above 1
  • That points straight at count = 1

Silent video: press play, pause any time.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal17 / 26

More tactics when you are stuck

1

Shrink it

Copy the failing part into a new cell with a tiny input. Small problems are easy to see.

2

Comment out

Put # before lines to switch them off, and find which line breaks things.

3

Restart and run all

Rules out the execution-order trap from Lecture 2.1 before you search any further.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal18 / 26

Asking for help, including AI tools

1

Try for 10 minutes

Follow the routine first. Struggling a little is where the learning happens.

2

Share the right things

The code, the full error message, what you expected, and what you already tried.

3

AI: explain, not write

Ask it to explain the error. Run and check anything it suggests. You must be able to explain every line you submit. [Course AI policy]

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal19 / 26

Bug hunt: fix all five

Each numbered part has exactly one bug. Parts 4 and 5 run without errors but give wrong answers. 15 minutes, in pairs.

Code
# 1
print("Total: " + 5)
# 2
name = "Nadia"
if name == "Nadia"
    print("Hi")
# 3
marks = [70, 85, 90]
print(marks[3])
# 4  should print the sum 15, once
total = 0
for i in range(1, 6):
    total = total + i
    print(total)
# 5  30 Celsius should give 86.0
celsius = 30
print(celsius * 9 / 5 + 23)
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal20 / 26

Solutions

Show these after students have tried the bug hunt.

Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal21 / 26

Solutions: the five fixes

1: use an f-string. 2: add the colon. 3: last position is 2. 4: print after the loop, not inside. 5: the constant is 32.

Code
print(f"Total: {5}")

name = "Nadia"
if name == "Nadia":
    print("Hi")

marks = [70, 85, 90]
print(marks[2])

total = 0
for i in range(1, 6):
    total = total + i
print(total)

celsius = 30
print(celsius * 9 / 5 + 32)
Output
Total: 5
Hi
90
15
86.0
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal22 / 26

Interactive lab: Debugging Lab

In the lab you can

  1. Error decoder12 broken programs: predict the error, then read the real Python message.
  2. Logic error huntTrace a vowel counter round by round and see why a + b / 2 is wrong.
  3. Notebook trapRun cells out of order, edit, restart, and see what the kernel remembers.
Open the lab ►︎

Opens in a new tab and works offline. All labs: labs/START_HERE.html

Screenshot of the Debugging Lab
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal23 / 26

Today's toolkit

Last line firstError type + message
Line numberWhere it failed; check the line above
Syntax / runtime / logicCan't read / crashes / wrong answer
print("x =", x)Show values while debugging
# lineSwitch a line off to test
Tiny inputShrink the problem
Restart + Run allRule out execution-order bugs
Known answerThe only way to catch logic errors
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal24 / 26

Homework 2.3

Due before Lecture 3.1 · [date]

1

Error diary

Create 5 different errors on purpose. For each: the code, the last line of the error, and one sentence explaining it.

2

Read, don't run

For the three bug-hunt slides, write the error type you expect before running. How many did you get right?

3

Debug with print

This should count words longer than 3 letters in "we love data science" but prints 0. Fix it using prints: count = 0; for w in text.split(): if len(w) > 3: count + 1.

4

Logic test

Write code for the average of 3 numbers. Test it with a case you can check in your head. Show the test.

5

Explain

In 3 sentences: why are logic errors harder to find than syntax errors?

Submit on [LMS / Google Classroom]: your notebook file HW2_3_<your ID>.ipynb, or a Colab link set to “Anyone with the link can view”.
Md Mahbub E NoorLecture 2.3: Finding and fixing mistakesUniversity of Barishal25 / 26