Debugging: Reading Error Messages and Fixing Bugs

Python for Absolute Beginners · Lesson 14

1 / 21

What you'll learn

2 / 21

Every programmer meets bugs

3 / 21

Reading an error message

score = 5
print(scroe)

Output:
Traceback (most recent call last):
  File "C:\python-course\bug1.py", line 2, in <module>
    print(scroe)
          ^^^^^
NameError: name 'scroe' is not defined. Did you mean: 'score'?
4 / 21

Read it from the bottom up

5 / 21

SyntaxError: the missing colon

age = 12
if age >= 10
    print("Old enough")

Output:
SyntaxError: expected ':'
6 / 21

SyntaxError: parentheses and = versus ==

print("Hello"

Output:
SyntaxError: '(' was never closed

if age = 12:

Output:
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
7 / 21

IndentationError

age = 12
if age >= 10:
print("Old enough")

Output:
IndentationError: expected an indented block after 'if' statement on line 2
8 / 21

NameError

print(Hello)

Output:
NameError: name 'Hello' is not defined
9 / 21

TypeError

print("Age: " + 12)

Output:
TypeError: can only concatenate str (not "int") to str
10 / 21

IndexError and KeyError

fruits = ["apple", "banana", "cherry"]
print(fruits[3])

Output:
IndexError: list index out of range

student = {"name": "Mia"}
print(student["age"])

Output:
KeyError: 'age'
11 / 21

ValueError

age = int("twelve")

Output:
ValueError: invalid literal for int() with base 10: 'twelve'
12 / 21

Error cheat sheet

ErrorIt usually meansCheck first
SyntaxErrorPython can't read the codeCheck colon, quotes, parentheses, = vs ==
IndentationErrorThe spaces are wrongIndent the line after a colon
NameErrorPython doesn't know the nameCheck typos, quotes, capital letters
TypeErrorWrong kinds of things togetherText plus a number?
IndexErrorThat list position doesn't existCount from 0
KeyErrorThat dictionary label doesn't existCheck the spelling
ValueErrorRight type, wrong valueDoes the text look like a number?
13 / 21

A four-step routine

  1. Read the last line
  2. Go to the line number, and look at the line above it
  3. Say what you expected and what happened
  4. Change one thing, then run it again

One change at a time, so you always know which change helped

14 / 21

Bugs with no error message

a = 10
b = 20
average = a + b / 2
print(average)

Output:
20.0
15 / 21

print() is your flashlight

total = 0
for number in range(1, 4):
    total = total + number
    print("number is", number, "total is", total)
print(total)

Output:
number is 1 total is 1
number is 2 total is 3
number is 3 total is 6
6
16 / 21

When you're stuck

17 / 21

Hands-on exercise

18 / 21

Key takeaways

19 / 21

Take the quiz

Take the Lesson 14 quiz: 5 quick questions to check what you learned.

20 / 21

Next lesson

Functions: Reusable Blocks

21 / 21

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.