SyntaxError: invalid syntax

This is the most common Python error and the most frustrating, because Python often points at a line that is perfectly correct.

Python
  File "shelf.py", line 1
    print("Hello"
         ^
SyntaxError: '(' was never closed

Why it points at the wrong line

Python reads your file forwards. When you leave a bracket open, it keeps reading, assuming the rest of the line is still coming — sometimes for several lines. The moment it finally gives up, it reports the position where things stopped making sense, not where you made the mistake.

So when a line looks fine, look at the line above it. That single habit resolves most of these.

The four causes, in order of how often they happen

1. An unclosed bracket, brace or quote

Python
print("Hello"          # ← the ( is never closed

Newer Python versions name it directly: '(' was never closed. Count your opening and closing brackets on the line above the one Python flagged.

2. A missing colon

Python
if price < 100
    print("Affordable")

Python
SyntaxError: expected ':'

Every if, elif, else, for, while, def and class line ends in a colon. Python tells you exactly which one is missing.

3. Using = where you meant ==

Python
if days = 1:
    print("Wash day")

Python
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

One equals sign puts a value into a name. Two ask whether things match. Python is being kind here and suggesting the fix outright — ignore the := part, you won’t need it for a long while.

4. A missing comma in a list or dictionary

Python
shelf = ["cleanser" "toner", "serum"]

No error, but no comma either — Python silently glues those two strings into "cleansertoner". Worse than a crash, because nothing tells you.

What to check, in order

  1. Look at the line above the one Python names
  2. Count brackets and quotes on that line
  3. Check for a missing : at the end of any block-opening line
  4. Check for = where you meant ==

Remember this

SyntaxError means Python couldn’t read your code, so nothing ran. That’s different from an error that appears partway through. Nothing is broken in your logic yet — Python hasn’t got far enough to have an opinion about it.


Thirty Python errors, each explained in full, in the Python Troubleshooting Handbook.

Next: NameError: name is not defined