SyntaxError
SyntaxError: invalid syntax
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("hello")
SyntaxError: invalid syntaxWhat causes this error
The source code contains tokens in an arrangement that does not conform to Python's grammar. Missing colons, unmatched brackets, incorrect operators, or illegal characters will all trigger this error before any code runs.
How to fix it
Read the traceback carefully — the caret (^) points to where the parser gave up. Check the indicated line and the line above it for missing colons, unmatched parentheses, or typos. Use an editor with syntax highlighting to spot issues faster.
Code that causes this error
if x == 5
print("hello")Fixed code
if x == 5:
print("hello")About SyntaxError
A SyntaxError is raised when the Python parser encounters source code that violates the language grammar rules. This is one of the most common errors beginners face and is detected before any code is executed. Python reads your source file and tries to parse it into an abstract syntax tree; when it finds tokens in an unexpected order or missing structural elements, it raises this exception.
Common triggers include missing colons after if/for/while/def/class statements, mismatched parentheses or brackets, using assignment operators where comparison operators are expected, and stray characters that Python cannot interpret. Because SyntaxError is caught during parsing, the traceback always points to the line where the parser got confused, which is sometimes the line after the actual mistake.
Common scenarios
Writing code with missing colons, parentheses, or brackets
Mixing Python 2 and Python 3 syntax when upgrading a codebase
Copy-pasting code from the web with formatting issues or invisible characters
Using reserved keywords as variable or function names