Readable code

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

Readable code · · Published 2026-11-30

Two women adjusting cables and switches on the panels of the ENIAC computer in 1946
Two ENIAC programmers preparing the machine for its public demonstration in February 1946, when every error was found by hand. U.S. Army photo, public domain, via Wikimedia Commons.

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 errorRuntime errorLogic error
When it appearsBefore anything runs, while the file is parsedWhile the program runs, on the failing lineAfter the program ends, when someone checks the result
What you seeSyntaxError, IndentationError or TabError, no "Traceback" headerA traceback ending in an exception such as TypeError, KeyError, ValueErrorNothing: a wrong number, a missing row, a file written in the wrong place
Depends on the input?No, it fails every timeOften: same code, different dataOften
Typical causesUnclosed bracket, missing colon, = for ==, bad indentation, pasted >>> promptsWrong type, missing key or file, division by zero, None where an object was expectedOff-by-one, wrong operator, wrong condition, units mixed up
What finds itThe interpreter, your editor, lintersRunning the code, tests with edge cases, type checkers for someTests, 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

For the twelve mistakes behind most cases, each with the exact message Python prints, see SyntaxError: invalid syntax, the 12 most common causes.

Sources