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.
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:
NameErroris the kind of problemscoreis 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.
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:
- the file name
- the line number
- the error type
- the short message
Do not try to understand every internal line at first.
For now, ask four questions:
- What line did Python point to?
- What kind of error is it?
- What name, value, or operation is mentioned?
- What is the smallest change I can test?
Common Error Types
You will see these often:
| Error | Usual meaning |
|---|---|
SyntaxError | Python could not parse the code |
NameError | a name was used before it had a value |
TypeError | an operation was used with the wrong kind of value |
IndexError | a list or sequence was indexed outside its range |
These names are not there to intimidate you. They are labels for debugging.
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.