I1 · Python Programming for AI

Reading Errors and Debugging

An error is Python's report that it cannot continue. A syntax error means the code breaks Python's grammar and nothing runs. An exception happens while the code runs, such as dividing by zero. The traceback shows where the error happened, and its last line names the error type and explains it. Debugging is finding and fixing the cause.

10 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

The error message looks scary. What is it actually telling you?

An error is Python's report that it cannot continue. A syntax error means the code breaks Python's grammar and nothing runs. An exception happens while the code runs, such as dividing by zero. The traceback shows where the error happened, and its last line names the error type and explains it. Debugging is finding and fixing the cause.

In simple words

Read the traceback from the bottom up. The last line says what went wrong, such as NameError: name 'scor' is not defined. The line number above it says where. Most errors are small: a typo, a missing quote, or a number added to text.

Why it matters

Every programmer, at every level, spends much of their time debugging. Reading errors calmly turns them from a wall into a signpost, and is the fastest way to become independent.

How it works

ErrorUsual causeExample
SyntaxErrorBroken grammar: missing quote, bracket or colonprint("hi)
IndentationErrorWrong spaces at the start of a lineAn extra space before print
NameErrorUsing a name that doesn't exist, often a typoprint(scor)
TypeErrorMixing types that don't go together10 + "5"
IndexErrorAsking for a position that doesn't exist[1, 2, 3][5]
ZeroDivisionErrorDividing by zero10 / 0
  1. Read the last line of the traceback: what type, and what message?
  2. Go to the line number it names.
  3. Print the values of variables just before that line.
  4. Change one thing, run again, and see what changed.

In code

Each broken line is run inside try, so the program keeps going and prints the error type and message instead of stopping.

reading_errors.py
def show_error(description, broken):
    try:
        broken()
    except Exception as error:
        print(description, "->", type(error).__name__ + ":", error)

show_error("Typo in a name", lambda: print(scor))
show_error("Number plus text", lambda: 10 + "5")
show_error("Position 5 of a 3-item list", lambda: [1, 2, 3][5])
show_error("Dividing by zero", lambda: 10 / 0)

Output

Typo in a name -> NameError: name 'scor' is not defined
Number plus text -> TypeError: unsupported operand type(s) for +: 'int' and 'str'
Position 5 of a 3-item list -> IndexError: list index out of range
Dividing by zero -> ZeroDivisionError: division by zero

Try it yourself

Which error is this?

Match each broken line to the error Python reports.

  • print("hello)
  • age = 15; print(agee)
  • "Score: " + 90
  • marks = [70, 80]; marks[2]
  • average = 100 / 0

Common mistakes

  • Reading the traceback from the top and getting lost. Start at the bottom.
  • Changing many things at once, so you don't know what fixed it.
  • Ignoring the line number. It points straight at the problem, or just after it.

Check yourself

Question 1

1. Which part of a traceback names the error type?

Question 2

2. 10 + "5" gives…

Question 3

3. What is the first debugging step?

Summary

  • Syntax errors stop the program before it runs; exceptions happen while it runs.
  • Read the traceback from the bottom: type, message, line number.
  • Debug by printing values and changing one thing at a time.

Finished reading?

Sources: Python docs: Errors and Exceptions