Understanding Syntax Errors
A syntax error occurs when the Python interpreter is unable to understand the structure of your code. This can be due to a variety of issues, such as missing parentheses or incorrect indentation.
Open up a new Python interpreter.
python3
Here is an example of a syntax error caused by a missing colon at the end of a for loop:
for i in range(10)
print(i)
The interpreter will raise a syntax error, and will tell us where the error occurred:
File "<stdin>", line 1
for i in range(10)
^
SyntaxError: invalid syntax
The caret symbol (^) indicates the location of the syntax error, and the error message tells us that the syntax is invalid.
To fix this syntax error, we simply need to add the colon at the end of the for loop:
for i in range(10):
print(i)
Now, let's try an example with incorrect indentation:
if True:
print("Hello, World!")
In this example, the print statement is not properly indented under the if statement. To fix this syntax error, we need to indent the print statement correctly:
if True:
print("Hello, World!")