Identify and Understand Common Python Errors
In this step, we will explore some common errors you might encounter when writing Python code and learn how to identify and understand the error messages. Encountering errors is a normal part of programming, and learning to read and interpret error messages is a crucial skill.
We will intentionally introduce some errors into our code to see how Python responds. Let's start by modifying the hello.py file we created in the first step.
Open the hello.py file in the VS Code editor.
First, let's introduce a spelling mistake in the print() function. Change the line to:
prunt("Hello, LabEx!")
Save the file (Ctrl + S).
Now, run the modified hello.py file from the terminal:
python hello.py
You should see an error message similar to this:
Traceback (most recent call last):
File "/home/labex/project/hello.py", line 1, in <module>
prunt("Hello, LabEx!")
NameError: name 'prunt' is not defined
This is a NameError. It tells us that the name prunt is not recognized by Python. This is because the correct function name is print. The error message also points to the file name (hello.py), the line number (line 1), and the specific code that caused the error.
Now, let's correct the spelling of print and introduce a missing quote. Change the line back to print, but remove the closing double quote:
print("Hello, LabEx!)
Save the file and run it again:
python hello.py
You should see a different error message, likely a SyntaxError:
File "/home/labex/project/hello.py", line 1
print("Hello, LabEx!)
^
SyntaxError: unterminated string literal (missing '"')
This SyntaxError indicates that there is an issue with the structure of your code. The message "unterminated string literal (missing '"')" clearly tells us that a string started with a double quote but did not end with one.
Finally, let's correct the quotes and introduce a non-English character for the parentheses. Change the line to:
print("Hello, LabEx!")
Note that the parentheses here are full-width Chinese characters, not the half-width English characters required by Python.
Save the file and run it:
python hello.py
You will likely see a SyntaxError related to invalid characters:
File "/home/labex/project/hello.py", line 1
print("Hello, LabEx!")
^
SyntaxError: invalid character '(' (U+FF08)
This error message points to the invalid character and its Unicode representation. Python expects standard English half-width characters for syntax elements like parentheses.
By intentionally creating these errors and observing the error messages, you can start to understand what different types of errors mean and how to locate the source of the problem in your code. In the next step, we will learn how to debug these errors.