Readable code

SyntaxError: invalid syntax in Python: the 12 Most Common Causes and How to Fix Them

Readable code · · Published 2026-11-26

A page of a 1947 computer logbook with handwritten times and notes, and a moth taped to the page above the words "First actual case of bug being found"
The Harvard Mark II logbook of 9 September 1947, with the moth found in a relay. Syntax errors are a gentler kind of bug: Python finds them before your code runs. U.S. Naval Historical Center, public domain, via Wikimedia Commons.

"SyntaxError: invalid syntax" is the message Python gives when it cannot even read your code. Nothing has run yet: the parser stopped at a point where the text no longer looks like Python. The good news is that the cause is nearly always one of a dozen small mistakes, and recent versions of Python name most of them precisely. This guide lists the twelve we see most, with the exact message each one produces and how to fix it.

What the message tells you

When Python reads a file, it first turns the text into tokens and then parses them against the grammar of the language. If the parser reaches a token that cannot fit anywhere, it raises SyntaxError with the file name, the line number, a copy of the line and a caret under the place it gave up. IndentationError and TabError are subclasses of SyntaxError, raised for problems with leading whitespace. The errors and exceptions chapter of the official tutorial explains the difference between these errors, which stop the program before it starts, and exceptions raised while it runs.

Since Python 3.10 the parser produces much more precise messages than before: the What's New in Python 3.10 page lists the new wording for unclosed brackets, missing colons, missing commas and other cases. If you are on an older version and see only "invalid syntax", upgrading is often the quickest way to a clearer message.

All the messages below were produced with Python 3.13; wording can differ slightly in other versions.

The 12 most common causes

1. A missing colon

if, elif, else, for, while, def, class, try, except, finally and with all end with a colon.

if x == 1
    pass
# SyntaxError: expected ':'

Fix: add the colon at the end of the line the caret points to.

2. A bracket, parenthesis or brace that was never closed

x = (1, 2
y = 3
# SyntaxError: '(' was never closed

Older versions reported this on the next line, which is why "the error is on a line that looks fine" is such a common complaint. Fix: count the brackets on the line named in the message, or let your editor highlight the matching pair.

3. = where you meant ==

if x = 1:
    pass
# SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

A single = assigns; == compares. Python does not allow a plain assignment inside a condition. Fix: use ==, or the walrus operator := if you really mean to assign and test in one go.

4. A missing comma

d = {"a": 1 "b": 2}
# SyntaxError: invalid syntax. Perhaps you forgot a comma?

The same message appears for function arguments (f(a b)) and list items. Fix: add the comma between the two items the caret underlines. The opposite mistake, a doubled comma such as [1, 2,, 3], gives a bare "invalid syntax".

5. An unterminated string

s = "abc
# SyntaxError: unterminated string literal (detected at line 1)

Fix: close the quote. For text across several lines, use triple quotes ("""…"""). Watch out for an apostrophe inside a single-quoted string: 'it's' ends the string after it.

6. Curly quotes pasted from a document

print(“hi”)
# SyntaxError: invalid character '“' (U+201C)

Word processors, chat apps and some web pages turn straight quotes into typographic ones. Python only accepts the straight ' and ". Fix: retype the quotes in a code editor. The same applies to long dashes and non-breaking spaces copied from a page.

7. Python 2 code run with Python 3

print "hello"
# SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?

except Exception, e:
# SyntaxError: multiple exception types must be parenthesized

Old tutorials and Stack Overflow answers are full of Python 2 syntax. Fix: print("hello") and except Exception as e:.

8. A keyword used as a name

class = 5
# SyntaxError: invalid syntax

True = 1
# SyntaxError: cannot assign to True

Words such as class, def, for, lambda, import and pass are reserved. Fix: pick another name; PEP 8 suggests a trailing underscore (class_) when the natural name is a keyword. The full list is in the keyword module documentation, or run import keyword; print(keyword.kwlist). Soft keywords such as match and case can still be used as ordinary names.

9. Indentation that does not line up

def f():
return 1
# IndentationError: expected an indented block after function definition on line 1

for i in range(3):
    print(i)
  print(i)
# IndentationError: unindent does not match any outer indentation level

Fix: indent each block by the same amount, four spaces per level as PEP 8 recommends, and never mix tabs and spaces. Our guide to indentation and line length covers the rules in detail.

10. An incomplete expression

x = 5 +
# SyntaxError: invalid syntax

x = 1 if y
# SyntaxError: expected 'else' after 'if' expression

Fix: finish the expression. To split a long expression over several lines, wrap it in parentheses rather than ending a line on an operator.

11. A number glued to a name

a = 3x
# SyntaxError: invalid decimal literal

Python has no implicit multiplication, and names cannot start with a digit. Fix: 3 * x, or rename the variable (x3).

12. Shell commands or prompts inside Python

pip install requests
# SyntaxError: invalid syntax

>>> x = 1
# SyntaxError: invalid syntax

The first is a terminal command typed into the Python interpreter or a script; the second is an example copied with its >>> prompt. Fix: run pip from your system shell (or python -m pip install requests), and strip the prompts from pasted examples.

When the caret points somewhere strange

The caret marks where the parser gave up, not necessarily where the mistake is. Three habits help:

  1. Read the line above. A missing closing bracket or colon at the end of one line often surfaces on the next.
  2. Check for an else or elif with nothing above it. An else: on its own, usually after an indentation slip, gives a bare "invalid syntax".
  3. Cut the file in half. If the message makes no sense, comment out the second half of the file and run it again, then narrow down. A syntax error is always local.

Catching syntax errors before you run

Every serious editor underlines syntax errors as you type. On the command line, python -m py_compile yourfile.py checks a file without running it, and linters such as flake8 (code E999) and ruff report syntax errors alongside style issues. Our guides to the pycodestyle error codes and to checking Python style locally show how to set this up so that a broken file never reaches a commit.

Sources