Concepts / Indentation and Code Blocks in Python

Indentation and Code Blocks in Python

Check spelling, capitalization, and leading whitespace whenever a short Python program fails unexpectedly.

  • Programming
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…

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.

Key point

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.

printbuilt-in output functionPrintdifferent name
What changes when the first letter is capitalized?
python
Output
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.

if conditionblock headerif conditionblock headerprint statementindentedprint statementtop levelcontains
How does changing leading whitespace affect whether a line is at the top level or inside an indented block?
python

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

Worked example

Removing an Accidental Indent

A top-level output statement has been given leading spaces accidentally. Determine what to inspect and how to correct it.

  1. 1
    Locate the failing line

    Read the IndentationError message and inspect the line it identifies.

  2. 2
    Inspect the line start

    Check whether the statement begins with spaces or a Tab even though it is intended to be a top-level statement.

  3. 3
    Remove leading whitespace

    Delete the accidental spaces or Tab so the statement begins at column 1.

  4. 4
    Check 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.

Result

The top-level statement is corrected when it has no leading spaces or tabs and begins at column 1.

Indented statementtop-level lineIndentationErrorinspect reported lineStatement at column1no leading whitespaceraisesremove spaces or Tab
How can a learner trace an indentation error from the reported line to the corrected line?

Debugging Checklist

  • Common mistake

    Writing Print instead of print.

    What it looks like
    Print("Hello")
    Why it fails

    Python is case-sensitive, so Print and print are different names. Only print is the built-in output function described here.

    Do this instead

    Use the exact lowercase spelling print.

  • Common mistake

    Leaving spaces or a Tab before a top-level statement.

    What it looks like
        print("Hello")
    Why it fails

    Top-level statements must start at column 1. Leading whitespace at the top level causes an IndentationError.

    Do this instead

    Remove all leading spaces or tabs from the beginning of the line.

  • Common mistake

    Assuming Python will infer the intended capitalization.

    What it looks like

    Using Print because a human reader would understand it as print.

    Why it fails

    Python follows exact naming rules rather than correcting a human-readable variation.

    Do this instead

    Compare the name character by character, including capitalization.

  • Common mistake

    Checking only the visible words and ignoring the start of the line.

    What it looks like

    A copied line contains an unnoticed leading space.

    Why it fails

    Leading whitespace can determine whether a line is valid at the top level or visibly belongs to an indented block.

    Do this instead

    Inspect the line's leading spaces and tabs whenever Python reports an IndentationError.

  1. 1
    If the message is NameError, inspect the exact spelling and capitalization of the name on the reported line.
  2. 2
    If the message is IndentationError, inspect the leading spaces and tabs on the reported line.
  3. 3
    For a top-level statement, remove leading whitespace so the statement begins at column 1.
  4. 4
    Check nearby lines for the same copied or auto-inserted whitespace problem.
  5. 5
    Run 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.

DetailPython's ruleDebugging questionBenefit
Capitalizationprint and Print are different namesDoes the name use the exact intended capitalization?Different names can remain distinct.
Top-level whitespaceA top-level statement must start at column 1Are there accidental spaces or tabs before the statement?The program's structure is not left to guesswork.
Indented structureLeading whitespace makes grouped statements visibly belong togetherDoes 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.

EASY

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

  1. 1
    Python is case-sensitive: print and Print are different names, and only print is the built-in output function described here.
  2. 2
    Leading spaces or tabs at the start of a top-level line cause an IndentationError; top-level statements must begin at column 1.
  3. 3
    Indentation makes it visible which statements belong together inside structured code.
  4. 4
    Use NameError messages to investigate spelling and capitalization, and IndentationError messages to investigate whitespace.
  5. 5
    Strict 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.
  • NameError and IndentationError messages provide useful places to begin debugging.
  • Python's strict rules prevent ambiguous interpretations and make program structure easier to read.

Related concepts

More concepts starting with I