Indentation and Code Blocks in Python
Check spelling, capitalization, and leading whitespace whenever a short Python program fails unexpectedly.
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
- 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.
- Tabs count as 8 columns and as 1; if the two ways of counting disagree about the block structure, it is a TabError.
- 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.
- 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.
- 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.
Loading the simulation…
Two Tiny Details
Python does not interpret code like a human reader. A human may understand that Print probably means the same thing as print, or that a line with a few accidental spaces should still be treated as a top-level statement. Python follows exact rules instead. Capitalization is part of a name, and whitespace at the beginning of a line affects how Python interprets that line. These details can make the difference between a program that runs and one that raises an error.
Check spelling, capitalization, and leading whitespace whenever a short Python program fails unexpectedly.
Names Depend on Capitalization
Python is case-sensitive. This means that print and Print are different names because their capitalization differs. Only print is the built-in output function described in this lesson. Writing Print does not cause Python to automatically correct the capitalization or infer what the programmer meant.
The first line uses the built-in output function. The second line uses the differently capitalized name Print and can result in a NameError.Whitespace Shows Structure
Leading whitespace means spaces or tabs placed before a line begins. At the top level, statements must start at column 1, which means they must have no leading spaces or tabs. If a top-level line begins with leading whitespace, Python raises an IndentationError. Inside structured code, indentation also makes it visible which statements belong together, so changing the leading whitespace can change whether a line is treated as part of an indented block or as a top-level line.
In this example, the leading whitespace before the print line makes the line visibly belong to the indented code block introduced by the if line. The important debugging distinction is that whitespace can be meaningful structure, not decoration. At the top level, an accidental space or Tab before a statement violates Python's rule that the statement must begin at column 1.
A Whitespace Trace
Removing an Accidental Indent
A top-level output statement has been given leading spaces accidentally. Determine what to inspect and how to correct it.
- 1Locate the failing line
Read the
IndentationErrormessage and inspect the line it identifies. - 2Inspect the line start
Check whether the statement begins with spaces or a Tab even though it is intended to be a top-level statement.
- 3Remove leading whitespace
Delete the accidental spaces or Tab so the statement begins at column 1.
- 4Check surrounding lines
Look for similar copied or auto-indented lines, because extra whitespace can be introduced by copying code or by an editor that automatically indents after Enter.
The top-level statement is corrected when it has no leading spaces or tabs and begins at column 1.
Debugging Checklist
Common mistake Writing Print instead of print.
What it looks likePrint("Hello")Why it failsPython is case-sensitive, so Print and print are different names. Only print is the built-in output function described here.
Do this insteadUse the exact lowercase spelling print.
Common mistake Leaving spaces or a Tab before a top-level statement.
What it looks likeprint("Hello")Why it failsTop-level statements must start at column 1. Leading whitespace at the top level causes an
IndentationError.Do this insteadRemove all leading spaces or tabs from the beginning of the line.
Common mistake Assuming Python will infer the intended capitalization.
What it looks likeUsing Print because a human reader would understand it as print.
Why it failsPython follows exact naming rules rather than correcting a human-readable variation.
Do this insteadCompare the name character by character, including capitalization.
Common mistake Checking only the visible words and ignoring the start of the line.
What it looks likeA copied line contains an unnoticed leading space.
Why it failsLeading whitespace can determine whether a line is valid at the top level or visibly belongs to an indented block.
Do this insteadInspect the line's leading spaces and tabs whenever Python reports an IndentationError.
- 1If the message is
NameError, inspect the exact spelling and capitalization of the name on the reported line. - 2If the message is
IndentationError, inspect the leading spaces and tabs on the reported line. - 3For a top-level statement, remove leading whitespace so the statement begins at column 1.
- 4Check nearby lines for the same copied or auto-inserted whitespace problem.
- 5Run the program again after correcting the specific mismatch.
Why Strict Rules Help
Case-sensitivity lets Python distinguish between related but different names, such as score and Score. Indentation makes code structure visible, so a reader can see which statements belong together. Together, these rules prevent code from having multiple possible interpretations. Python requires the programmer to state the details exactly, so the program means one clear thing rather than depending on a reader's guess.
| Detail | Python's rule | Debugging question | Benefit |
|---|---|---|---|
| Capitalization | print and Print are different names | Does the name use the exact intended capitalization? | Different names can remain distinct. |
| Top-level whitespace | A top-level statement must start at column 1 | Are there accidental spaces or tabs before the statement? | The program's structure is not left to guesswork. |
| Indented structure | Leading whitespace makes grouped statements visibly belong together | Does the line have the indentation expected for its block? | Code structure is readable at a glance. |
Python's exact rules connect debugging details with clear program structure.
A program reports a NameError on a line that uses Print. What exact detail should you inspect first? A different program reports an IndentationError on a top-level output line. What should you inspect at the beginning of that line?
Hints
- Compare print and Print character by character.
- Look for spaces or a Tab before the top-level statement.
Essential Takeaways
- 1Python is case-sensitive: print and Print are different names, and only print is the built-in output function described here.
- 2Leading spaces or tabs at the start of a top-level line cause an
IndentationError; top-level statements must begin at column 1. - 3Indentation makes it visible which statements belong together inside structured code.
- 4Use
NameErrormessages to investigate spelling and capitalization, andIndentationErrormessages to investigate whitespace. - 5Strict naming and indentation rules prevent ambiguous code and make Python programs readable and unambiguous.
At a glance
- Python treats capitalization as part of a name, so print and Print are not interchangeable.
- Leading whitespace is meaningful: top-level statements must begin at column 1, while indentation makes grouped code visible.
NameErrorandIndentationErrormessages provide useful places to begin debugging.- Python's strict rules prevent ambiguous interpretations and make program structure easier to read.