Playground / Syntax Errors and Indentation

Break a program, read Python's report

Syntax Errors and Indentation

Interactive lab

Try it: Syntax Errors and Indentation

How Python checks a program's structure before running any of it: the tokenizer tracks indentation with a stack (INDENT and DEDENT), the parser groups lines into blocks after each colon, and when something is wrong Python reports the exact SyntaxError, IndentationError or TabError with the line, a caret under the spot and hints like "Did you mean '=='".

How it works

  1. The tokenizer reads each line's leading spaces: deeper than the top of the indentation stack is an INDENT (pushed), shallower pops DEDENTs until it matches, and a width that matches no open level is an IndentationError.
  2. Tabs count as 8 columns and as 1; if the two ways of counting disagree about the block structure, it is a TabError.
  3. Inside ( [ { line breaks and indentation are ignored, so a missing ) swallows the following lines; Python reports "'(' was never closed" when the error is found on a later line.
  4. The parser matches statements: a header such as if, for, while, def or else must end with ':' and be followed by an indented block; = where a condition is expected, or a keyword used as a name, is invalid syntax.
  5. Python stops at the first error and prints File, line, the source line, a caret (^) under the columns it blames, and the error type and message; no line of the program has run.

Default run (4 steps): main.py has 7 lines. Before running any of it, Python compiles the whole file: the tokenizer splits each line into tokens and tracks indentation, and the parser groups the statements into blocks. … Python stops: SyntaxError: expected ':' (line 2). No line of the program has run.

Simplified: The programs are fixed and you break them with one menu choice at a time. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. Only the error kinds offered in the menu are modelled.

Educational simulation

Loading the simulation…