Reading error messages and debugging, step by step
Introduction to Data Science and Machine Learning · Md Mahbub E Noor · University of Barishal
print("Total: " + 5)
# TypeError: can only concatenate
# str (not "int") to strPython cannot read the code: a missing colon, bracket or quote. Nothing in the cell runs.
The code starts, then crashes at one line: a wrong name, a wrong type, a missing file.
No message at all, but the answer is wrong. The hardest kind, because Python is happy.
Traceback (most recent call last):
File "shop.py", line 6, in <module>
print("Average: " + average)
~~~~~~~~~~~~^~~~~~~~~
TypeError: can only concatenate str (not "float") to str
Error type and message. Say in your own words what Python is complaining about.
Go to the line number. Check that line and the one just above it.
Change one thing only, then run again. Several changes at once hide what fixed it.
Print the values involved, shrink the problem, then ask for help with the full error.
| Error | Usually means | Typical fix |
|---|---|---|
| SyntaxError | Missing colon, bracket or quote | Look at the marked spot and the line above |
| IndentationError | Block not indented, or mixed spacing | Indent the block by 4 spaces |
| NameError | Name misspelled or never created | Check spelling; run the cell that creates it |
| TypeError | Wrong type for the operation | Convert: int(), str(), or an f-string |
| ValueError | Right type, impossible value | Check the value: int("ten") cannot work |
| IndexError | Position past the end of a list | Positions run from 0 to len - 1 |
| KeyError | Dictionary key does not exist | Use d.get(key, 0) or check the key |
| ZeroDivisionError | Dividing by zero | Check the divisor first, for example empty lists |
| FileNotFoundError | File not where Python looks | Put the file next to the notebook |
| ModuleNotFoundError | Library not installed | Lab: use Anaconda. Home: pip install |
age = "20" next_year = age + 1 print(next_year)
This cell fails. Which line, and why? Decide before you run it.
age = "20" next_year = age + 1 print(next_year)
TypeError: can only concatenate str (not "int") to str
"20" in quotes is text, not a numberage = 20, or convert with int(age)input() often arrives as textscores = [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.
scores = [70, 85, 90]
total = 0
for s in scores:
total = total + s
average = total / len(score)NameError: name 'score' is not defined
score was never created: the list is scoreslen(scores)marks = [] average = sum(marks) / len(marks) print(average)
This cell fails. Which line, and why? Decide before you run it.
marks = [] average = sum(marks) / len(marks) print(average)
ZeroDivisionError: division by zero
if len(marks) > 0:a = 70 b = 90 average = a + b / 2 print(average)
Expected average of 70 and 90: 80. What does it print?
a = 70 b = 90 average = a + b / 2 print(average)
115.0
(a + b) / 2word = "banana"
count = 0
for ch in word:
if ch in "aeiou":
count = 1
print(count)1
ch and countcount = 1 sets instead of addscount = count + 1, then delete the debug printword = "banana"
count = 0
for ch in word:
if ch in "aeiou":
count = 1
print("ch =", ch, "count =", count)
print(count)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
WATCH FOR
Silent video: press play, pause any time.
Copy the failing part into a new cell with a tiny input. Small problems are easy to see.
Put # before lines to switch them off, and find which line breaks things.
Rules out the execution-order trap from Lecture 2.1 before you search any further.
Follow the routine first. Struggling a little is where the learning happens.
The code, the full error message, what you expected, and what you already tried.
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]
Each numbered part has exactly one bug. Parts 4 and 5 run without errors but give wrong answers. 15 minutes, in pairs.
# 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)Show these after students have tried the bug hunt.
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.
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)Total: 5 Hi 90 15 86.0
In the lab you can
Opens in a new tab and works offline. All labs: labs/START_HERE.html
Last line first | Error type + message |
Line number | Where it failed; check the line above |
Syntax / runtime / logic | Can't read / crashes / wrong answer |
print("x =", x) | Show values while debugging |
# line | Switch a line off to test |
Tiny input | Shrink the problem |
Restart + Run all | Rule out execution-order bugs |
Known answer | The only way to catch logic errors |
Due before Lecture 3.1 · [date]
Create 5 different errors on purpose. For each: the code, the last line of the error, and one sentence explaining it.
For the three bug-hunt slides, write the error type you expect before running. How many did you get right?
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.
Write code for the average of 3 numbers. Test it with a case you can check in your head. Show the test.
In 3 sentences: why are logic errors harder to find than syntax errors?
Watch it again at home to revise.