Explanation
SyntaxError occurs when Python encounters code that violates the language's syntax rules. Unlike in compiled languages, Python detects syntax errors at runtime when it tries to parse the file. Common causes include missing colons after if/for/while/def/class statements, incorrect indentation, unmatched parentheses or brackets, using = instead of == in conditions, and wrong keyword usage. Python shows the line with the error and points to the exact position.
Common Causes
- Missing colon after control structure
- Incorrect indentation
- Unmatched brackets or parentheses
- Using assignment in conditions
- Wrong keyword spelling
Solution
Check the line number and position indicated in the error message. Verify all control structures have colons (if:, for:, while:, def:, class:). Ensure parentheses, brackets, and braces are properly matched. Check indentation consistency (use spaces, not tabs). Verify comparison operators (== vs =). Use an IDE with Python syntax highlighting to catch errors in real-time. Run python -m py_compile filename.py to syntax check without execution.
Code Example
# Missing colon - SyntaxError
if x > 5 # missing colon!
print("yes")
# Fix
if x > 5:
print("yes")
# Wrong indentation
if True:
print("hello") # IndentationError
# Fix
if True:
print("hello")
# Unmatched bracket
data = [1, 2, 3 # SyntaxError
# Fix
data = [1, 2, 3]
# Check syntax without running
python -m py_compile script.py
Error Information
Language
python
Difficulty
Beginner
Views
116
Related Errors
Python
Python RuntimeWarning: coroutine was never awaited
An async coroutine was created but never awaited, so it never executed.
Python
Python PIL/Pillow Image Not Found
The PIL/Pillow library cannot locate an image file at the specified path.
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.
Python
Python TypeError: argument of type is not iterable
The code tries to iterate over a value that is not iterable.