Working with errors in Python
When there is an error the program does not run (or stops) and Python shows an error message that has the line number and the kind of error. The most common one is SyntaxError: a quote or bracket is not closed, or a writing rule of the language is broken. NameError appears when an unknown name is used: the variable has not been given a value, or the name is spelled differently letter by letter, for example Print instead of print. An extra space at the start of a line gives an IndentationError, because indentation is also part of the rules for Python. To fix an error, read the message from the end, check the line it points to (and the line before it if needed), correct it and run the program again. Finding errors is an everyday part of a programmer’s job, so do not be afraid of the message – it helps you.
| Error | Cause |
|---|---|
| SyntaxError | a quote or bracket is not closed, a writing rule is broken |
| NameError | an unknown name is used |
| IndentationError | an extra space at the start of a line |
In a notebook a teacher marked a mistake in red and wrote the line and the reason. A program’s error message helps in just the same way.
Programmers, testers and editors find the line of a mistake, read the reason and fix it.
Take a finished piece of homework and find one mistake in it. Write a short “error message” for it, as Python would: the line, the kind of mistake and how to fix it.
1print("Salom)SyntaxError
1print(nom)NameError
“Error hunter”: pairs give each other a 3-line code with one error inside; the partner names the kind of error, points to the line and fixes it. (Read the error message together.)