SyntaxError: invalid syntax
1 · The lesson
readWhat 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 — or just past — where Python got confused. The real mistake is often a character or two earlier.
When you see it
>>> if x == 1 File "<stdin>", line 1 if x == 1 ^ 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:
def greet(name) print(name)
Fix: add the colon — def greet(name):.
2. Unclosed bracket, paren, or brace:
nums = [1, 2, 3 print(nums)
The error often appears on the next line, not the offending one, because Python keeps reading until it gives up. Fix: close the [.
3. Using = instead of == in a condition:
if x = 1: print("one")
Fix: if x == 1:.
4. Python 2 print statement:
print "hello"Fix: print("hello").
5. Using a reserved word as a variable name:
class = "intro"
Fix: rename to cls, klass, or course_class. Same applies to for, if, return, lambda, def, import, etc.
6. Missing comma in a list, tuple, or function call:
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. Python often notices the problem one line late, especially with unclosed brackets and missing colons. Walk 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 visible at a glance.
When the error message is just invalid syntax with no detail, Python 3.10+ tries to be more specific (expected ':', was never closed). Upgrading Python often gives much clearer messages.
When you'd actually see this in real code
- Pasting a multi-line snippet from a blog post where the closing brace got truncated.
- Refactoring an
ifinto anelifand forgetting to change the indentation or colon. - Copying Python 2 examples from old Stack Overflow answers.
Related errors
See Also
- All Python errors — the full index, by type and by when it happens.
- Python syntax cheat sheet
- Reading tracebacks tutorial