1.6 Error messages
Learning objectives
By the end of this section you should be able to
- Identify the error type and line number in error messages.
- Correct syntax errors, name errors, and indentation errors.
How to read errors
A natural part of programming is making mistakes. Even experienced programmers make mistakes when writing code. Errors may result when mistakes are made when writing code. The computer requires very specific instructions telling the computer what to do. If the instructions are not clear, then the computer does not know what to do and gives back an error.
When an error occurs, Python displays a message with the following information:
- The line number of the error.
- The type of error (Ex:
SyntaxError). - Additional details about the error.
Ex: Typing print "Hello!" without parentheses is a syntax error. In Python, parentheses are required to use print. When attempting to run print "Hello!", Python displays the following error:
Traceback (most recent call last):
File "/home/student/Desktop/example.py", line 1
print "Hello"
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello")?
The caret character (^) shows where Python found the error. Sometimes the error may be located one or two lines before where the caret symbol is shown because Python may not have discovered the error until then. Traceback is a Python report of the location and type of error. The word traceback suggests a programmer trace back in the code to find the error if the error is not seen right away.
Learning to read error messages carefully is an important skill. The amount of technical jargon can be overwhelming at first. But this information can be very helpful.
Common types of errors
Different types of errors may occur when running Python programs. When an error occurs, knowing the type of error gives insight about how to correct the error. The following table shows examples of mistakes that anyone could make when programming.
| Mistake | Error message | Explanation |
|---|---|---|
print("Have a nice day!" | SyntaxError: unexpected EOF while parsing | The closing parenthesis is missing. Python is surprised to reach the end of file (EOF) before this line is complete. |
word = input("Type a word: ) | SyntaxError: EOL while scanning string literal | The closing quote marks are missing. As a result, the string does not terminate before the end of line (EOL). |
print("You typed:", wird) | NameError: name 'wird' is not defined | The spelling of word is incorrect. The programmer accidentally typed the wrong key. |
prints("You typed:", word) | NameError: name 'prints' is not defined | The spelling of print is incorrect. The programmer accidentally typed an extra letter. |
print("Hello")
| IndentationError: unexpected indent | The programmer accidentally typed a space at the start of the line. |
print("Goodbye")
| IndentationError: unexpected indent | The programmer accidentally pressed the Tab key at the start of the line. |