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:

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

You can’t handle SyntaxError exceptions using tryexcept blocks because they occur before the code executes. You need to fix the code to resolve the error:

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 March 26, 2025 • Reviewed by Martin Breuss