PromptHub
Python Beginner 12 views

Python SyntaxError

Python detected invalid syntax in the source code.

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

12

Related Errors