A Python syntax error means the parser could not read your code, and the message names the rule you broke: expected ':', '(' was never closed, unterminated string literal and so on. Read the message, look at the line it reports and the line just above it, and compare against the examples below.
The messages below are those documented for Python 3.10 and newer, which reworded many of them. Older versions say a plain invalid syntax far more often. Any output shown is example output, and paths are shortened.
How to read a syntax error
This is the example from the official tutorial:
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^^^^^
SyntaxError: invalid syntax
Three parts matter:
- File name and line number. Line numbers start at 1. For a script this is the first place to look.
- The line, with carets. The carets underline the token where the parser first found the code invalid. The tutorial is explicit that this is not always the place that needs fixing. Here
printis underlined, but the real problem is the missing colon just before it. - The message. Newer Python versions often tell you the fix directly.
The exception object also carries these as attributes: filename, lineno, offset (the column, starting at 1), text, and since 3.10 end_lineno and end_offset. Editors use them to place the squiggle. For other error types, see how to read a Python traceback.
The common syntax errors at a glance
| Message | Usual cause | Fix |
|---|---|---|
SyntaxError: expected ':' | Missing colon after if, for, while, def, class | Add the colon |
SyntaxError: '(' was never closed | An opening bracket with no match | Add the closing bracket |
SyntaxError: invalid syntax. Perhaps you forgot a comma? | Two items in a list, dict or call with no comma between them | Add the comma |
SyntaxError: unterminated string literal | A quote that is never closed on its line | Close the quote |
SyntaxError: cannot assign to ... here. Maybe you meant '==' instead of '='? | Single = inside a condition | Use == |
IndentationError: ... | Wrong indentation | See the IndentationError guide |
Missing colon
Code, from the Python 3.10 release notes:
if rocket.position > event_horizon
Output:
File "<stdin>", line 1
if rocket.position > event_horizon
^
SyntaxError: expected ':'
Every statement that opens a block (if, elif, else, for, while, def, class, try, except, with) must end its first line with a colon. Add it at the end of the line and indent the body.
Unclosed bracket or parenthesis
Code, also from the release notes (the closing } is missing):
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
some_other_code = foo()
Python 3.10 and newer report:
File "example.py", line 1
expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
^
SyntaxError: '{' was never closed
Before 3.10 the same code reported invalid syntax on line 3, nowhere near the cause. Inside brackets Python keeps reading across lines, so it swallows the following statements until it gives up. If you see this message, go to the line it names and check that every (, [ and { after that point has a partner. On older Python versions, an error on a line that looks fine usually means an unclosed bracket on the line above.
Missing comma
Code, from the release notes:
items = {
x: 1,
y: 2
z: 3,
Output:
File "<stdin>", line 3
y: 2
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
The line after y: 2 needed a comma at the end. The same message appears for function calls and lists where two values sit side by side with no comma. The message is a guess, so confirm that a comma is actually what is missing.
Unterminated string
A string opened with ' or " must be closed by the same quote on the same line. The language reference's grammar excludes newlines from single-quoted strings; only triple-quoted strings may span lines. So this fails:
s = 'abc
def'
with SyntaxError: unterminated string literal, and recent versions add the line where it was detected. Three fixes, depending on what you meant:
- Close the quote:
s = 'abc'. - Use triple quotes for a real multi-line string:
s = '''abcthen a new line thendef'''. - End the line with a backslash inside the string to continue it without a newline in the value. The reference says the backslash and newline are ignored.
Quotes inside the text are the usual trigger. The reference's own example: "Don't do that!" works because the outer quotes differ from the apostrophe. 'Don't do that!' does not.
= instead of == in a condition
Code, from the release notes:
if rocket.position = event_horizon:
File "<stdin>", line 1
if rocket.position = event_horizon:
^
SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
= assigns, == compares. The wording changes with the left side (here it is an attribute, rocket.position); the hint about == is the part to act on.
Other messages added in Python 3.10
The release notes also list these messages, which are worth recognising:
multiple exception types must be parenthesized: writeexcept (TypeError, ValueError):, notexcept TypeError, ValueError:.expected 'except' or 'finally' block: atrywith neither.':' expected after dictionary keyandexpression expected after dictionary key and ':': a dictionary entry is incomplete.
Reserved words as names
The language reference lists the hard keywords (class, def, for, in, is, pass, return and others) as unusable as ordinary identifiers. Using one as a variable name, for example class = 5, is a syntax error. Rename it; a trailing underscore (class_) is a common convention.
A method for finding the cause
- Read the message first. On 3.10 or newer it often names the fix.
- Go to the reported line, then read the line above it. The parser reports where it got confused, which is often one line after the mistake.
- Check brackets and quotes opened earlier in the file, not only on the reported line.
- Check which Python version you are running with
python --version. If the message is a bareinvalid syntax, an older version is likely, and upgrading gives clearer messages. - If the code was copied from a web page or chat and the message mentions an indent or an illegal character, see the IndentationError guide.
Catching a SyntaxError in code
A syntax error in the running file cannot be caught, because the file is never executed. It can be caught when code is compiled at runtime:
try:
compile("if True\n x = 1\n", "<demo>", "exec")
except SyntaxError as error:
print(error.msg, error.lineno, error.offset)
The Python reference says SyntaxError can be raised by import, compile(), exec(), eval(), or when reading the initial script. IndentationError and TabError are subclasses, so except SyntaxError catches them as well.
Frequently asked questions
- What is a syntax error in Python?
- A syntax error means Python could not parse your code because it breaks the grammar of the language. It is raised while the file is being read, before any line runs, so a script with a syntax error prints the error and nothing else.
- Why does the error point at a different line than the mistake?
- The parser reports where it first noticed the problem, not where the mistake was made. The Python tutorial says this is not always the place that needs to be fixed. A missing closing bracket is the classic case: the error often shows up on the next line or later. Python 3.10 and newer report unclosed brackets at the opening bracket instead.
- Can I catch a SyntaxError with try/except?
- Only when the bad code is compiled at runtime, for example through import, compile(), exec() or eval(). A syntax error in the file you are running is raised before any try block executes, so it cannot be caught there.
- Is a syntax error different from an exception like NameError?
- Yes. A syntax error is found while parsing, before the program runs. Errors such as NameError or TypeError happen while the program is running, on the line that triggers them. Code with a syntax error never starts.