Skip to content

Module 2 · Python Syntax and Fundamentals — topic 14 of 14

Syntax errors

Read and fix SyntaxError and IndentationError messages: what the caret points to, why the reported line can be after the real mistake, and the most common causes.

Beginner 14 min read·Lesson 28 of 306 in Python Programming

Learning objectives

  • Read a SyntaxError message and locate the problem
  • Recognise the most common causes
  • Use compile() to check code for syntax errors

Definition

Read and fix SyntaxError and IndentationError messages: what the caret points to, why the reported line can be after the real mistake, and the most common causes.

Introduction

A syntax error means Python couldn’t understand your code because it breaks the grammar rules. Python reports it before running anything, along with the file, the line number and a caret (^) pointing to where it got confused.

Why it matters

Syntax errors are the most frequent errors when you start, and they are always fixable by reading the message carefully. Building the habit now means you spend seconds rather than minutes on them.

Detailed explanation

A typical message has three parts: the location (File "app.py", line 4), the offending line with a caret underneath, and the error type with a short explanation, such as SyntaxError: expected ':'.

Modern Python gives helpful hints: “'(' was never closed”, “invalid syntax. Perhaps you forgot a comma?”, or “unterminated string literal”.

The reported line is where Python noticed the problem, which is sometimes after the real mistake. An unclosed bracket on line 3 may be reported on line 4, so check the line before as well.

IndentationError is a kind of SyntaxError about leading spaces: “expected an indented block”, “unexpected indent” or “unindent does not match any outer indentation level”.

Common causes: missing colon, unclosed bracket or quote, = instead of ==, using a keyword as a name, and missing commas in lists.

Syntax

Python
compile(source_text, "filename.py", "exec")
  • compile() parses code without running it.
  • It raises SyntaxError if the text is invalid.
  • The error object has lineno and msg attributes describing the problem.

Code examples

A missing colon (shown, not run)

Python
if marks > 40
print("pass")

Python stops with SyntaxError: expected ':' and the caret points to the end of the first line.

Checking text for errors

Python
try:
compile("print('hi'", "demo.py", "exec")
except SyntaxError as err:
print("Line", err.lineno, "-", err.msg)
Output
Line 1 - '(' was never closed

More examples

Diagnosing several broken snippets

Python
snippets = {
"missing colon": "for i in range(3)\n print(i)",
"bad indent": "x = 1\n y = 2",
"keyword as name": "class = 5",
"valid": "total = sum([1, 2, 3])",
}
for label, code in snippets.items():
try:
compile(code, label, "exec")
print(f"{label}: OK")
except SyntaxError as err:
print(f"{label}: {type(err).__name__} on line {err.lineno}")
Output
missing colon: SyntaxError on line 1
bad indent: IndentationError on line 2
keyword as name: SyntaxError on line 1
valid: OK

Step-by-step explanation

  • snippets maps a label to a small piece of Python source code.
  • compile() parses each snippet without executing it.
  • If parsing fails, the except block reports the error type and line number.
  • IndentationError appears for the unexpected indent because it is a subclass of SyntaxError.

Expected output

Running “Diagnosing several broken snippets” prints exactly:

TextOutput
missing colon: SyntaxError on line 1
bad indent: IndentationError on line 2
keyword as name: SyntaxError on line 1
valid: OK

Practical applications

  • Editors run the same parser in the background to underline syntax errors as you type.
  • Continuous-integration checks reject commits that contain syntax errors before tests run.
  • Tools that accept Python snippets from users, such as notebooks, check syntax before running anything.

Best practices

  • Read the last line of the message first, then the caret.
  • Check the line before the reported one for unclosed brackets or quotes.
  • Fix one error at a time and rerun.

Common mistakes

Looking only at the reported line

Avoid

values = [1, 2, 3
print(values) # error reported here

Prefer

values = [1, 2, 3]
print(values)

The bracket opened on line 1 was never closed; Python only noticed on line 2.

Using = in a condition

Avoid

if score = 100:

Prefer

if score == 100:

= assigns; == compares. Python suggests “Maybe you meant '==' or ':=' instead of '='?”

Key takeaways

  • Syntax errors are grammar mistakes found before the program runs.
  • The caret shows where Python got confused; the real mistake may be just before it.
  • IndentationError is a special kind of SyntaxError.

Try it yourself

  1. 1
    Write three deliberately broken lines (missing colon, unclosed quote, = in an if) and read each error message carefully before fixing them.
  2. 2
    Use compile() to check whether "while True print(1)" is valid, and print the error message.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Python Syntax and Fundamentals” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat happens when this code runs?
  • BeginnerWhich line is a comment in Python?
  • BeginnerWhich of these is a Python keyword?
Practise this module