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

"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:
- Read the line above. A missing closing bracket or colon at the end of one line often surfaces on the next.
- Check for an
elseorelifwith nothing above it. Anelse:on its own, usually after an indentation slip, gives a bare "invalid syntax". - 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
- Python Software Foundation, "Errors and Exceptions", The Python Tutorial, consulted 26 November 2026.
- Python Software Foundation, "What's New In Python 3.10", section on better error messages.
- Python Software Foundation, "keyword: Testing for Python keywords", Python standard library documentation.
- Error messages reproduced by Four Spaces with CPython 3.13 on 26 November 2026.
PEP 8 rulesIndentation and line length
Four spaces, no tabs, 79 characters: where these numbers come from, how to wrap long lines cleanly and which warnings point to each problem.
Linterspycodestyle error codes
What E225, E302, E501 or W291 actually mean and how to fix each one: a family-by-family reference to the codes used by pycodestyle, flake8 and ruff.
LintersCheck style locally
Install a checker in a virtual environment, run it on your project, configure it once and let it fix what it can: pycodestyle, flake8 and ruff step by step.