What Is a Syntax Error in Python? Syntax vs Runtime vs Logic Errors

A syntax error is a line of code that Python cannot read. It is not a wrong answer or a crash in the middle of your program: Python refuses to start at all. That single fact separates it from the two other kinds of mistakes every programmer meets, runtime errors and logic errors, and knowing which one you are facing tells you where to look.
The short definition
Before Python executes a file, it parses it: it checks that the text follows the grammar of the language and turns it into an internal structure the interpreter can run. A syntax error is any text that breaks that grammar, such as a bracket that is never closed, a missing colon or an = where Python expects a comparison. The official tutorial calls them "parsing errors" and notes, fairly, that they are "perhaps the most common kind of complaint you get while you are still learning Python" (Python tutorial, Errors and Exceptions).
Because parsing happens first, a syntax error anywhere in a file stops the whole file. Even the lines above the mistake never run. Here is a two-line script whose first line would fail with a NameError if it were ever executed:
print(undefined_name)
print("never reached"
Python 3.13 does not complain about undefined_name. It reports the unclosed bracket on line 2 and stops:
File "g.py", line 2
print("never reached"
^
SyntaxError: '(' was never closed
This is the quickest test you can apply: if the traceback has no "Traceback (most recent call last)" header and names SyntaxError (or its relatives IndentationError and TabError), nothing in the file has run yet.
Runtime errors: the code starts, then stops
A runtime error happens while the program is running, on a line that is grammatically fine but impossible to carry out with the values it receives at that moment. Python raises an exception, and unless your code catches it, prints a traceback and stops. Three common ones:
print("4" + 4) # TypeError: can only concatenate str (not "int") to str
prices = {"tea": 2}
print(prices["coffee"]) # KeyError: 'coffee'
def average(xs):
return sum(xs) / len(xs)
print(average([])) # ZeroDivisionError: division by zero
Each of these lines parses perfectly. average works for every list except the empty one, which is the point: a runtime error depends on the data. The same program can run for months and fail the first time a user submits an empty form. A runtime traceback always starts with "Traceback (most recent call last):" and lists the chain of calls that led to the failing line, which is why it is read from the bottom up.
Since Python 3.11, tracebacks also underline the exact sub-expression that failed with ~ and ^ markers, a change described in PEP 657. In print(prices["coffee"]) the markers sit under prices["coffee"] rather than under the whole line, which saves time on long expressions.
Logic errors: no message at all
A logic error is code that parses, runs to the end and produces the wrong result. Python has no way to know what you meant, so it prints nothing. A classic is an off-by-one loop:
def total(prices):
s = 0
for i in range(1, len(prices)): # starts at index 1, skips the first price
s += prices[i]
return s
print(total([5, 10, 20])) # prints 30, the right answer is 35
Logic errors are the expensive kind because they surface late, sometimes in production, sometimes never noticed. The tools that catch them are not the parser but tests that compare actual and expected results, assertions in the code, and reviews by a second pair of eyes. Our guide to readable tests with pytest shows how a three-line test would have flagged total immediately.
The three side by side
| Syntax error | Runtime error | Logic error | |
|---|---|---|---|
| When it appears | Before anything runs, while the file is parsed | While the program runs, on the failing line | After the program ends, when someone checks the result |
| What you see | SyntaxError, IndentationError or TabError, no "Traceback" header | A traceback ending in an exception such as TypeError, KeyError, ValueError | Nothing: a wrong number, a missing row, a file written in the wrong place |
| Depends on the input? | No, it fails every time | Often: same code, different data | Often |
| Typical causes | Unclosed bracket, missing colon, = for ==, bad indentation, pasted >>> prompts | Wrong type, missing key or file, division by zero, None where an object was expected | Off-by-one, wrong operator, wrong condition, units mixed up |
| What finds it | The interpreter, your editor, linters | Running the code, tests with edge cases, type checkers for some | Tests, assertions, code review |
Is IndentationError a syntax error?
Yes. In Python's exception hierarchy IndentationError is a subclass of SyntaxError, and TabError is a subclass of IndentationError, as the reference page on built-in exceptions shows. All three are raised while parsing:
File "h.py", line 2
y = 2
IndentationError: unexpected indent
A NameError for a misspelled variable, on the other hand, is a runtime error. Python only discovers that totl does not exist when it reaches the line, which is why a typo inside a rarely used branch can hide for a long time. Linters such as pyflakes, Ruff or Pylint report undefined names without running the code, one of the strongest arguments for checking your code locally before every commit.
How to fix a syntax error quickly
- Read the last line first. Since Python 3.10 the messages are specific ("'(' was never closed", "expected ':'", "Maybe you meant '==' or ':=' instead of '='?"), as the What's New in Python 3.10 notes describe.
- Look at the line before. The caret marks where the parser gave up, which is often one line after the real mistake, typically an unclosed bracket or string.
- Check without running.
python -m py_compile file.pyparses a file and reports syntax errors without executing anything, handy for scripts that would otherwise send e-mails or write files. - Let the editor help. Any editor with a Python language server underlines syntax errors as you type, long before you run the file.
For the twelve mistakes behind most cases, each with the exact message Python prints, see SyntaxError: invalid syntax, the 12 most common causes.
Sources
- Python documentation, tutorial chapter 8, "Errors and Exceptions": syntax errors versus exceptions, and how tracebacks are read.
- Python documentation, "Built-in Exceptions": the exception hierarchy, including SyntaxError, IndentationError and TabError.
- PEP 657, "Include Fine Grained Error Locations in Tracebacks" (Python 3.11).
- What's New in Python 3.10: the section on better error messages.
- All error messages on this page were produced with CPython 3.13 on 30 November 2026.
Readable codeSyntaxError: invalid syntax
A missing colon, an unclosed bracket, = instead of ==, a pasted >>> prompt: twelve causes, the message each one prints, and how to read the caret.
LintersCheck style locally
Install a checker in a virtual environment, run it on your project, configure it once and let it fix what it can: pycodestyle, flake8 and ruff step by step.
Readable codeReadable tests with pytest
A failing test is a message to whoever reads it next. Names that state a behaviour, one action per test, plain asserts and fixtures that hide set-up without hiding meaning.