πŸ”§ Error Fixes
Β· 2 min read
Last updated on

Python SyntaxError: Invalid Syntax β€” How to Fix It


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, or try
  • 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 ruff or flake8 that 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
πŸ“˜