PythonMastery
reference 4 min read · lesson 18 of 60 in Errors

SyntaxError: invalid syntax

1 · The lesson

read

What this error means

Python could not parse your source code. The parser ran into something it didn't understand and stopped before your program even started running. The arrow ^ in the traceback points at the place where Python got confused, or just after it. The real mistake is often a character or two earlier.

When you see it

python
>>> class = "intro"
  File "<stdin>", line 1
    class = "intro"
          ^
SyntaxError: invalid syntax

Why it happens

Always a typo or a structural mistake. Here are the six most common causes.

1. Missing colon after if, for, while, def, class, try, else:

python
def greet(name)
    print(name)

Fix: add the colon: def greet(name):.

2. Unclosed bracket, paren, or brace:

python
nums = [1, 2, 3
print(nums)

Python 3.10 and later point at the line with the open [ and say '[' was never closed. Older versions often pointed at the next line instead, because Python kept reading until it could not continue. Fix: close the [.

3. Using = instead of == in a condition:

python
if x = 1:
    print("one")

Fix: if x == 1:.

4. Python 2 print statement:

python
print "hello"

Fix: print("hello").

5. Using a reserved word as a variable name:

python
class = "intro"

Fix: rename to cls, klass, or course_class. The same applies to for, if, return, lambda, def, import, etc.

6. Missing comma in a list, tuple, or function call:

python
items = [1, 2, 3 4, 5]

Fix: add the comma: [1, 2, 3, 4, 5].

How to fix it

Read the line the traceback points at, and the line above it. Older Python versions often noticed the problem one line late, especially with unclosed brackets. Read the code from the top of the function or block, character by character, until you reach the marker.

If your editor has syntax highlighting and bracket matching, use them: an unclosed ( is usually easy to see.

Python 3.10 and later show a more specific message for many of these mistakes. A missing colon (cause 1) gives expected ':', an unclosed bracket (cause 2) gives '[' was never closed, and a missing comma (cause 6) gives invalid syntax. Perhaps you forgot a comma?. Older versions show only invalid syntax, so upgrading Python often gives much clearer messages.

When you'd see this in real code

  • Pasting a multi-line snippet from a blog post where the closing brace got truncated.
  • Refactoring an if into an elif and forgetting to change the indentation or colon.
  • Copying Python 2 examples from old Stack Overflow answers.

See Also

Found this useful? Share it with a friend who’s learning Python.