Review

Core idea

An error is evidence. It tells you which assumption the program could not keep.

Tracebacks

Read near the bottom first.

PartMeaning
error typethe kind of failure
messagethe operation or assumption that failed
file and linewhere Python was executing
failing linethe expression to inspect first

Syntax errors

A syntax error means Python could not parse the program.

Common causes:

  • missing colon after if, for, while, or def;
  • unclosed quote, parenthesis, bracket, or brace;
  • indentation that does not match the expected block.

Fix syntax before debugging logic.

Name errors

A NameError means Python could not find a name.

Common causes:

  • typo;
  • name used before assignment;
  • name assigned only in a branch that did not run;
  • local name used outside its function.

Type errors

A TypeError means an operation received a value of an unsuitable type.

Good questions:

  • What operation failed?
  • What type did the operation expect?
  • What type did the value actually have?
  • Should I convert at the boundary?

Index errors

An IndexError means an index is outside a sequence.

For a sequence of length n, valid positive indexes are:

0 through n - 1

Prefer direct iteration when you do not need the index:

Assertions

Use assertions to state assumptions while developing:

assert len(values) > 0, "values must not be empty"

Assertions are for programmer assumptions. Public user input usually needs normal checks and helpful responses.

Reducing failures

A reduced failing example:

  • still fails;
  • removes unrelated code;
  • keeps the operation or assumption being tested.

Change one thing at a time and run again.