SyntaxError means your Python code has invalid syntax that violates Python's grammar rules. The error message usually points near the problem. Common issues are missing colons, incorrect indentation, or mismatched parentheses.
The "SyntaxError" error means Python's parser found code that doesn't follow Python's syntax rules. Unlike runtime errors, this happens before code even runs. Common causes: 1. **Missing colons**: if/for/while/def/class statements need a colon at the end 2. **Indentation errors**: Python requires consistent indentation 3. **Mismatched brackets**: Parentheses, brackets, or quotes not balanced 4. **Wrong syntax**: Using Python 2 syntax in Python 3 or vice versa 5. **Special characters**: Invalid encoding or non-ASCII characters Python will refuse to run the file until syntax is fixed.
Look at the traceback - the error is usually near the reported line:
File "script.py", line 42
if x > 5 # Missing colon!
^
SyntaxError: invalid syntaxCheck the line above too, as the real error might be there.
Common Python 2 vs 3 issues:
# Python 2 (wrong in Python 3)
print "Hello" # Missing parentheses
except Exception, e: # Wrong syntax
# Python 3 (correct)
print("Hello")
except Exception as e:Python is sensitive to indentation. Use spaces consistently (no tabs):
if x > 5:
print("Greater than 5") # Indented with spaces
print("Wrong") # Wrong indentation - mixes levelsEnsure all parentheses, brackets, and quotes are balanced:
# Wrong
mylist = [1, 2, 3
result = func(param1, param2
# Correct
mylist = [1, 2, 3]
result = func(param1, param2)Tools catch syntax errors before runtime:
pip install pylint flake8
pylint your_script.py
flake8 your_script.pyMost IDEs highlight syntax errors immediately. Use IDE's syntax checker or a pre-commit hook to catch these before running code.
SyntaxError: 'await' outside async function
How to fix "SyntaxError" in Python
SyntaxError: 'break' outside loop
How to fix "SyntaxError" in Python
SyntaxError: cannot assign to function call
How to fix "SyntaxError" in Python
ValueError: math domain error
How to fix "ValueError: math domain error" in Python
ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: '/usr/lib/python3/dist-packages'
How to fix "Permission denied" when installing packages with pip