SyntaxError: invalid syntax means Python could not parse your code: the structure or punctuation does not follow the language’s rules. The traceback usually points to the line (and sometimes the character) where parsing failed. Fixing it is often a matter of adding a missing colon or quote, or correcting an operator. This guide lists common causes and fixes.
What this error means
Before running your program, Python turns source code into an internal structure. If something is wrong—a missing :, an unmatched bracket or quote, or = where == is required—the parser stops and raises SyntaxError: invalid syntax, often with a caret (^) showing where it got stuck. Related: IndentationError, TabError.
Common causes
- Missing colon. After
if,elif,else,for,while,def,class,with, ortryyou must write:before the block. - Wrong operator in condition. Use
==for comparison, not=(assignment). Writingif x = 5:is a syntax error. - Unmatched quotes, parentheses, or brackets. Every
",',(,[,{must have a matching closing character on the same line or across continued lines. - Invalid names. Variable names cannot start with a digit or be a keyword (e.g.
class,def,if).
Example that causes the error
if x = 5 # SyntaxError: use == for comparison
print("x is 5")
def greet() # SyntaxError: missing :
print("Hello")
name = "Alice # SyntaxError: missing closing quote
Fix: correct the syntax
if x == 5:
print("x is 5")
def greet():
print("Hello")
name = "Alice"
Use the traceback
Python shows the file name and line number. Look at that line (and the line before if the error is “unexpected EOF”) for:
- Missing
:afterif,for,while,def,class - Unmatched
"'([{ - Using
=instead of==in conditions - Reserved words used as variable names
Next steps: Errors & Exceptions · IndentationError · TabError · Getting Started