Beginner   Chapter 109 · 25 min read · Module 9: Exception Handling

Syntax Errors

Learning objectives
  • After this chapter you can explain what a syntax error is and why Python reports it before the program runs.
  • You can read the file, line number, caret and message of a syntax error.
  • You can fix common causes such as missing colons, unclosed brackets and quotes, and wrong indentation.
  • You can tell the difference between SyntaxError, IndentationError and TabError.
  • You can use compile() to check a piece of code for syntax errors safely.

Every language has grammar rules, and Python is no different. When you write code that breaks those rules, Python cannot even understand what you mean, so it refuses to run the program. The message you get is called a syntax error. It is the first kind of problem that most beginners meet.

Syntax errors are easy to fix once you know where to look. Python tells you the file, the line and often points at the place with a small arrow. In this chapter you will learn how to read that report, and you will see the mistakes that cause most syntax errors in real code.

You will also learn the difference between a syntax error and an exception, which is an error that appears while a correct program runs. Keeping these two ideas apart helps you find bugs faster.

What is a syntax error?

Syntax error: a mistake in the structure of the code that breaks the grammar rules of Python, so the program cannot be understood or started

Before Python runs a file, it reads the whole file and turns it into an internal form. If the text does not follow the grammar, this step fails and Python stops with a SyntaxError. Because this happens before execution, not even the first line of your program runs. If a file has a syntax error on its last line, nothing at all is printed by the earlier lines.

This is the main difference from an exception. An exception such as ZeroDivisionError happens while the program is running, so earlier lines have already done their work. A syntax error means the file is not valid Python, and the program never starts.

Reading the message

A syntax error report shows the file name, the line number, the line of code, a row of carets that points to the place where Python got confused, and the error name with a short message. The pointer shows where Python noticed the problem, which can be a little after the real mistake. If the marked line looks fine, check the line before it, because an unclosed bracket or quote often shows up on the next line.

Example 1: a missing colon (not run)
age = 20
if age >= 18
    print("adult")
File "demo.py", line 2 if age >= 18 ^ SyntaxError: expected ':'
The exact words of messages change between Python versions. Python 3.10 and newer give clearer messages, such as expected ':' or '(' was never closed. The idea is always the same.

Common causes and their fixes

  • A missing colon at the end of if, for, while, def, class, else or try lines.
  • An unclosed bracket, parenthesis, brace or quote. Python then keeps reading the next lines as part of the same expression.
  • Using a single = in a condition where == is needed, as in if x = 5:.
  • Using a reserved word, such as class or for, as a variable name.
  • Missing commas between items in a list or call, or an extra comma in the wrong place.
  • Using the wrong kind of quote, or mixing text quotes in a way that ends the string early.
  • Wrong indentation, which gives an IndentationError.

Python 3.10 also added a helpful hint for many of these. For example, it can point at the opening bracket that was never closed, or suggest that you meant ==. Read the whole message and not only the error name.

Indentation errors

Python uses indentation to mark blocks. If a block is missing its indented lines, or if lines inside one block have different indentation, Python raises IndentationError, which is a kind of SyntaxError. TabError appears when tabs and spaces are mixed in a confusing way. The advice is simple: use four spaces for each level and never mix tabs and spaces.

Example 2: fixed versions of broken code
age = 20
if age >= 18:
    print("adult")

items = [1, 2, 3]
print(len(items))

x = 5
if x == 5:
    print("five")
adult 3 five

Checking code with compile()

The built-in compile(source, filename, mode) checks text without running it. If the text has a syntax error, it raises SyntaxError, and you can catch that exception because compile runs at your run time. The exception object has lineno for the line number and msg for the message. This is also how tools such as editors can mark errors while you type. Never use this to run unknown code, because compile only checks it, and exec would execute it.

Example 3: catching a SyntaxError with compile
snippets = [
    "x = 1 + 2",
    "if x > 1\n    pass",
    "print('hi'",
    "for i in range(3):\nprint(i)",
]
for text in snippets:
    try:
        compile(text, "<snippet>", "exec")
        print("ok")
    except IndentationError:
        print("IndentationError")
    except SyntaxError as e:
        print("SyntaxError")
ok SyntaxError SyntaxError IndentationError
Example 4: the class tree of syntax errors
print(issubclass(IndentationError, SyntaxError))
print(issubclass(TabError, IndentationError))
print(issubclass(SyntaxError, Exception))
print(issubclass(SyntaxError, ValueError))
True True True False

A calm way to fix syntax errors

Start with the line Python shows, then look at the line above it. Check that every opening bracket and quote has a closing partner, that every block header ends with a colon, and that the indentation is regular. Fix one error at a time and run again, since Python reports only the first problem it finds, and one mistake can cause several messages. A good editor with colour, bracket matching and automatic indentation prevents many of these mistakes.

Python syntax

Syntax
if condition:
    statement
Syntax
for item in items:
    statement
Syntax
compile(source_text, "<name>", "exec")

Real-world applications

  • Fixing code you typed in an editor before it runs.
  • Checking user supplied formulas or scripts for valid syntax.
  • Building editor tools and linters that mark errors while you type.
  • Learning to read error messages quickly in exams and interviews.

Common mistakes

Mistake: Forgetting the colon at the end of an if, for, while or def line.
Fix: End every block header with a colon and indent the lines that follow.
Mistake: Leaving a bracket or quote open.
Fix: Count opening and closing partners; let the editor highlight matching pairs.
Mistake: Writing = instead of == in a condition.
Fix: Use == to compare and = only to assign.
Mistake: Mixing tabs and spaces for indentation.
Fix: Use four spaces everywhere and configure the editor to insert spaces.
Mistake: Looking only at the marked line when the real problem is earlier.
Fix: Also check the previous line for a missing bracket, quote or comma.

Important tips

  • Read the full message, not only the name of the error.
  • Fix errors from the top; later ones may disappear.
  • Use an editor with bracket matching and syntax colours.

Key points summary

  • A syntax error stops the program before any line runs.
  • The message shows the line, a caret and a short explanation.
  • IndentationError and TabError are special kinds of SyntaxError.
  • compile() can check code for syntax errors without running it.

Exam and interview points

  • Syntax errors are detected at parse time, before execution.
  • IndentationError is a subclass of SyntaxError; TabError is a subclass of IndentationError.
  • A missing colon after if, for, while, def or class is a very common syntax error.
  • Use == for comparison and = for assignment.

Quick revision

  • Syntax error: bad grammar, program does not start.
  • Check the line shown and the line above it.
  • Colons, brackets, quotes and indentation cause most errors.
  • Exceptions are run time problems; syntax errors are not.

Frequently asked questions

Why does my program print nothing before a syntax error?

Python checks the whole file first. If any part is invalid, the program never starts, so no line runs.

Can I catch a syntax error with try and except?

Not in the same file, since the file cannot start. You can catch it when it comes from compile, exec or eval on text at run time.

Why does Python point at a line that looks correct?

The real mistake is often on the line before, such as an open bracket or quote that makes Python read on.

Is IndentationError a different thing from SyntaxError?

It is a subclass. Every IndentationError is also a SyntaxError.

Practise this chapter

22 practice questions Take the chapter quiz

Related chapters