Reading Output and Errors

Programs communicate in two common ways:

  • output: what the program intentionally prints
  • errors: what Python reports when it cannot run something

Both are useful. Output tells you what happened. Errors tell you where Python got stuck. A beginner does not need to understand every line of an error report at once. The first job is to find the useful part.

Ordinary Output

This program prints two lines:

Output:

starting
5.0

The output is evidence. In later experiments, you may print a loss value, an array shape, or a few predictions for the same reason: to inspect the run.

Read ordinary output

Run this and compare the code with the two printed lines.

Runs locally with Python in your browser.

Ready to run.

A Simple Error

This program uses a name before giving it a value:

print(score)

If score was never defined, Python reports a NameError.

The most useful part is usually near the end:

NameError: name 'score' is not defined

Read it slowly:

  • NameError is the kind of problem
  • score is the name Python could not find
  • "not defined" means no value was assigned to that name before use

A useful error

Run this to see Python report the missing name.

Runs locally with Python in your browser.

Ready to run.

Tracebacks Point to a Line

When a script fails, Python prints a traceback. It can look noisy, but the last few lines are often enough for a beginner.

Look for:

  1. the file name
  2. the line number
  3. the error type
  4. the short message

Do not try to understand every internal line at first.

For now, ask four questions:

  1. What line did Python point to?
  2. What kind of error is it?
  3. What name, value, or operation is mentioned?
  4. What is the smallest change I can test?

Common Error Types

You will see these often:

ErrorUsual meaning
SyntaxErrorPython could not parse the code
NameErrora name was used before it had a value
TypeErroran operation was used with the wrong kind of value
IndexErrora list or sequence was indexed outside its range

These names are not there to intimidate you. They are labels for debugging.

Exercise: Read the error

If Python says NameError: name 'loss' is not defined, which name is missing?

Answer it first, then check.

HintRead the quoted text

The error message places the missing name between quotation marks.

SolutionThe missing name is loss

NameError: name 'loss' is not defined identifies loss as the name Python could not find. The error type describes the category; the quoted text names the specific missing value handle.

Errors Are Reports

An error is not a dead end. It is a report. Read the last useful line, identify the broken assumption, change one thing, and run again.