SyntaxError: invalid syntax
What causes this
Pythonβs parser hit something it canβt understand. The tricky part: the error often points to the line after the actual mistake, because Python only realizes something is wrong when it tries to parse the next line. Common causes:
- Missing colon after
if,for,def,class,while,with, ortry - Unclosed parentheses, brackets, or quotes on the previous line
- Using Python 2 syntax in Python 3
- Using a reserved keyword as a variable name
Fix 1: Missing colon
The most common cause. Every compound statement needs a colon:
# β Missing colon
if x > 5
print("big")
for item in items
process(item)
def greet(name)
return f"Hello {name}"
# β
Add the colon
if x > 5:
print("big")
for item in items:
process(item)
def greet(name):
return f"Hello {name}"
Fix 2: Unclosed parentheses or brackets
Check the line before the error. An unclosed (, [, or { causes the error to appear on the next line:
# β Missing closing parenthesis on line 1
data = dict(
name="Alice",
age=30
# Python reports the error on the NEXT line
print(data) # SyntaxError here!
# β
Close the parenthesis
data = dict(
name="Alice",
age=30,
)
print(data)
Same with strings:
# β Unclosed string
message = "Hello world
print(message) # SyntaxError!
# β
Close the string
message = "Hello world"
Fix 3: Python 2 vs Python 3
If youβre running Python 3 with Python 2 syntax:
# β Python 2 print statement
print "hello"
# β
Python 3 print function
print("hello")
# β Python 2 exception syntax
except ValueError, e:
# β
Python 3
except ValueError as e:
Check your Python version:
python --version
Fix 4: Reserved keywords as variable names
Python has reserved words you canβt use as variable names:
# β 'class', 'return', 'import', 'from', etc. are reserved
class = "Math"
return = True
# β
Use different names
class_name = "Math"
should_return = True
Full list of reserved words: False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
Fix 5: Assignment in wrong context
# β Can't use assignment in an expression (before Python 3.8)
if x = 5: # SyntaxError!
# β
Use == for comparison
if x == 5:
# β
Or use walrus operator := (Python 3.8+)
if (x := get_value()) > 5:
How to prevent it
- Use an editor with Python syntax highlighting β itβll show unclosed brackets and strings visually
- Use a linter like
rufforflake8that catches syntax errors before you run the code - When you see a SyntaxError, always check the line before the reported line β thatβs often where the real problem is
- If youβre learning Python, keep the Python cheat sheet handy for syntax reference Related: Python AssertionError β How to Fix It