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
Traceback (most recent call last):
File "<exec>", line 1
pip install numpy
^^^^^^^
SyntaxError: invalid syntaxThe fix
[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.
2. A Python keyword used as a variable name
This raises the error
Traceback (most recent call last):
File "<exec>", line 1
class = "Biology"
^
SyntaxError: invalid syntaxThe fix
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.
3. A missing comma between items
This raises the error
Traceback (most recent call last):
File "<exec>", line 1
scores = [90, 85 77, 64]
^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?The fix
[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.
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 rinstead of3.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
pipandpythoncommands in a terminal, never inside a.pyfile.
Related errors
All Python errors · How to read a traceback · Step through your code