Home·Error messages

python · Python

The message

SyntaxError: invalid syntax

What it means

The parser could not make a statement out of what it found there, and the cause is usually the line before the one it points at rather than that line itself. An unclosed bracket or quote, a missing colon, or Python 2's print "x" are the common causes — with an unclosed bracket the parser keeps going for several lines before giving up. python -m py_compile app.py checks the syntax without running anything, and since 3.10 the messages are far more specific, so upgrading Python is itself a diagnostic.

The fix

python -m py_compile app.py
Printed by
python
Python
18

A Python traceback splits the answer in two — the last line says what went wrong, the frames above it say where — so reading only the last line gives you the name and loses the place, and for the value-is-missing errors such as NoneType and KeyError the cause almost always sits in a frame above the one that crashed.

Reading an error message

  • Read from the first line down. The lower you go the more it is about the tool’s internals; the cause is usually at the top.
  • If there is a file and a line number, start there — not the top stack frame, but the topmost line that names a file you wrote.
  • Search the message verbatim, but strip your own paths and variable names first; those are what stop the search from matching.
  • The same condition is worded differently across tool versions. If results look wrong, add the version number to the query.
  • Before pasting a fix, check what it throws away. Some of these cannot be undone.

Common questions

Q. What does “SyntaxError: invalid syntax” mean?

The parser could not make a statement out of what it found there, and the cause is usually the line before the one it points at rather than that line itself. An unclosed bracket or quote, a missing colon, or Python 2's print "x" are the common causes — with an unclosed bracket the parser keeps going for several lines before giving up. python -m py_compile app.py checks the syntax without running anything, and since 3.10 the messages are far more specific, so upgrading Python is itself a diagnostic.

Q. How do I fix it?

python -m py_compile app.py — before running it, check the explanation above for what this command discards.

Q. Which tool prints this?

python. It sits under Python, and the message runs to 3 words.

Errors nearby