Skip to main content

Syntax Errors

A Syntax Error occurs when Python's interpreter tries to read your code but finds that you have violated the grammatical rules of the Python language.

Think of this like writing an English sentence with incorrect grammar or punctuation (e.g., "The cat sat on the. table"). Because the structure is broken, the listener (or in this case, the Python interpreter) cannot make sense of it.

If your code contains even a single syntax error, Python will refuse to execute the program at all.


Common Causes of Syntax Errors

Here are the most frequent syntax mistakes that beginners make, along with how Python reports them and how to fix them:

1. Missing Colons (:)

In Python, colons are required at the end of control flow headers like if, else, for, while, and function definitions (def).

Incorrect Code:

# Missing colon at the end of the if statement
if age >= 18
print("You can vote")

Python's Error Message:

SyntaxError: expected ':'

Correct Code:

if age >= 18:
print("You can vote")

2. Unclosed Parentheses, Brackets, or Braces

Every opening bracket must have a matching closing bracket. If you forget to close one, Python gets confused.

Incorrect Code:

# Missing closing parenthesis for print
print("Hello, World!"

Python's Error Message:

SyntaxError: unexpected EOF while parsing

(Note: EOF stands for "End of File". Python reached the end of the file expecting a closing parenthesis but never found it.)

Correct Code:

print("Hello, World!")

3. Mismatched or Unclosed Quotes

Strings must start and end with matching quote marks (either single quotes ' or double quotes ").

Incorrect Code:

# Double quote opened but single quote closed
message = "Hello, World!'

Python's Error Message:

SyntaxError: unterminated string literal

Correct Code:

message = "Hello, World!"

4. Incorrect Indentation (IndentationError)

Python uses indentation (blank spaces) to define blocks of code. An incorrect indentation level will throw an IndentationError, which is a specific type of Syntax Error.

Incorrect Code:

def greet():
# Code inside the function must be indented
print("Hello!")

Python's Error Message:

IndentationError: expected an indented block after function definition

Correct Code:

def greet():
print("Hello!")

How to Fix Syntax Errors

  1. Read the Error Message: Python will point a caret (^) at the exact line and position where it thinks the error occurred.
  2. Check the Line Before: Sometimes the mistake is actually on the line just before the one pointed out by Python (e.g., a missing closing bracket or quote on the previous line).
  3. Use an IDE: Modern code editors like VS Code will highlight syntax errors with red squiggly lines before you even run the code.