Skip to content

SyntaxError

SyntaxError is a built-in exception that occurs when the interpreter encounters a line of code that violates Python’s syntax rules.

This type of error is typically raised when there’s an issue with the structure of the code, such as a missing colon, unmatched parentheses, or incorrect keyword usage.

As a developer, you won’t handle SyntaxError exceptions. Instead, you’ll need to fix the syntax issue to resolve the error. Syntax errors are usually caught during the initial parsing of the code, before execution begins.

SyntaxError Occurs When

  • Forgetting a colon at the end of a function or control statement
  • Using incorrect indentation or mixing tabs and spaces
  • Misspelling a keyword or using a keyword improperly
  • Omitting or mismatching parentheses, brackets, or quotes

SyntaxError Example

An example of when the exception appears:

Language: Python
>>> numbers = [1, 2, 3 4]
  File "<stdin>", line 1
    numbers = [1, 2, 3 4]
                     ^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

You typically won’t handle SyntaxError exceptions with tryexcept blocks because most syntax errors are caught when Python parses the source file before execution begins. The exception is when you parse code at runtime with compile(), exec(), eval(), or import, in which case you can catch a SyntaxError like any other exception. In most cases, though, you’ll need to fix the code to resolve the error:

Language: Python
>>> numbers = [1, 2, 3, 4]

You don’t raise SyntaxError exceptions manually. They’re automatically raised by Python when it parses the code.

Tutorial

Invalid Syntax in Python: Common Reasons for SyntaxError

In this step-by-step tutorial, you'll see common examples of invalid syntax in Python and learn how to resolve the issue. If you've ever received a SyntaxError when trying to run your Python code, then this is the guide for you!

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 8, 2026 • Reviewed by Martin Breuss