Python's "invalid syntax" error message comes up often, especially when you're first learning Python. What usually causes this error and how can you fix it?
Table of contents
- What is a
SyntaxError
in Python? - Causes of
SyntaxError: invalid syntax
- Fixing
SyntaxError: invalid syntax
- Upgrading Python improves error messages
- Count your parentheses
- Misspelled, missing, or misplaced keywords
- Subtle spacing problems
- Forgotten quotes and extra quotes
- Mixing up your symbols
- Indentation errors in disguise
- Embedding statements within statements
- Errors that appear only in the Python REPL
- Problems copy-pasting from the REPL
- The line number is just a "best guess"
- SyntaxError exceptions happen all the time
What is a SyntaxError
in Python?
This is Python's way of saying "I don't understand you". Python knows that what you've typed isn't valid Python code but it's not sure what advice to give you.
When you're lucky, your SyntaxError
will have some helpful advice in it:
$ python3 greet.py
File "/home/trey/greet.py", line 10ifname=="Trey"
^
SyntaxError: expected ':'
$ python3 greet.py
File "/home/trey/greet.py", line 10ifname=="Trey"
^
SyntaxError: expected ':'
But if you're unlucky, you'll see the message invalid syntax
with nothing more:
$ python3.9 greet.py
File "/home/trey/greet.py", line 4
name
^
SyntaxError: invalid syntax
$ python3.9 greet.py
File "/home/trey/greet.py", line 4
name
^
SyntaxError: invalid syntax
This error message gives us no hints as to what might be going on outside of a line number and a bit of highlighting indicating where Python thinks the error occurred.
Causes of SyntaxError: invalid syntax
What are the likely causes …