Editor

SyntaxError: invalid syntax

What it means

Python could not make sense of a line, so it stopped before running any of your program. The caret ^ under the code shows where Python got confused, and the real mistake is there or just before it. Sometimes Python adds a hint, such as Perhaps you forgot a comma?.

1. A terminal command typed into the editor

This raises the error

Broken
pip install numpy
import numpy as np
print(np.arange(5))
Output
Traceback (most recent call last):
  File "<exec>", line 1
    pip install numpy
        ^^^^^^^
SyntaxError: invalid syntax

The fix

Fixed
import numpy as np
print(np.arange(5))
Output
[0 1 2 3 4]

pip install is a command for a terminal, not Python code, so it cannot go in a .py file. In this editor you can skip it: common packages such as numpy and pandas are set up for you the first time you import them.

Try fixing it yourself in the editor

2. A Python keyword used as a variable name

This raises the error

Broken
class = "Biology"
print("My class is", class)
Output
Traceback (most recent call last):
  File "<exec>", line 1
    class = "Biology"
          ^
SyntaxError: invalid syntax

The fix

Fixed
class_name = "Biology"
print("My class is", class_name)
Output
My class is Biology

Words like class, def, for, if, import, pass and lambda are reserved by Python. Adding a word or an underscore makes a name of your own.

Try fixing it yourself in the editor

3. A missing comma between items

This raises the error

Broken
scores = [90, 85 77, 64]
print(scores)
Output
Traceback (most recent call last):
  File "<exec>", line 1
    scores = [90, 85 77, 64]
                  ^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

The fix

Fixed
scores = [90, 85, 77, 64]
print(scores)
Output
[90, 85, 77, 64]

Items in a list, tuple, dictionary or function call are separated by commas. Python found two values side by side and guessed that a comma was missing.

Try fixing it yourself in the editor

When you see this error, check

  • Look at the caret ^ and at the line before it. A mistake at the end of one line is often reported on the next.
  • Check for a missing operator between two values, such as 3.14 r instead of 3.14 * r.
  • Make sure no variable is named after a keyword: class, def, import, from, lambda, pass, global.
  • Check that brackets and quotes come in pairs.
  • Run pip and python commands in a terminal, never inside a .py file.

All Python errors · How to read a traceback · Step through your code