SyntaxError
PythonERRORCommonSyntax ErrorHIGH confidence

Invalid syntax

What this means

Raised when the Python parser encounters a piece of code that does not conform to the language's syntax. This error means the code is not grammatically correct Python, and it cannot be executed.

Why it happens
  1. 1Missing a colon at the end of a statement like `if`, `for`, `def`, or `class`.
  2. 2Mismatched or missing parentheses, brackets, or braces.
  3. 3Using a Python reserved keyword (e.g., `class`, `for`) as a variable or function name.
How to reproduce

This error is triggered by code that is not structurally valid, such as a malformed `if` statement.

trigger — this will error
trigger — this will error
# Missing a colon at the end of the if statement
x = 10
if x > 5
  print("x is greater than 5")

expected output

  File "<stdin>", line 3
    print("x is greater than 5")
    ^
SyntaxError: invalid syntax

Fix 1

Add the missing colon

WHEN When using compound statements like `if`, `else`, `for`, `while`, `def`, or `class`.

Add the missing colon
x = 10
if x > 5:  # Colon added here
  print("x is greater than 5")

Why this works

The colon signifies the beginning of an indented code block that belongs to the statement.

Fix 2

Correct keyword usage

WHEN When you accidentally use a reserved keyword as a variable name.

Correct keyword usage
# 'class' is a keyword, use a different name
klass = "Economics" 
print(klass)

Why this works

Renaming the variable to something that is not a reserved keyword resolves the conflict.

Code examples
Triggerpython
x = 10
if x > 5
    print(x)  # SyntaxError: invalid syntax (missing colon)
Handle in exec()python
code = "if x > 5"
try:
    compile(code, "<string>", "exec")
except SyntaxError as e:
    print(f"Syntax error at line {e.lineno}: {e.msg}")
Avoid with a linterpython
# Run before executing:
# python -m py_compile script.py
# or: flake8 script.py
# Both catch SyntaxError before runtime.
What not to do

Ignoring syntax errors reported by your IDE or linter

Syntax errors are fatal. They prevent the program from running at all and must be fixed before execution.

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors