Pylerno
English

Syntax and indentation

Read a block of code and explain how indentation controls its structure.

On this page

The concept

Python uses indentation to mark blocks. A colon introduces a block in statements such as if; the lines inside it begin farther to the right. Use four spaces for each indentation level. Lines at the original indentation level are outside that block.

In this lesson, if True simply means the block runs. You will study conditions later. Concentrate on the relationship between alignment and execution. A comment begins with # and is ignored by Python. A docstring is a string used as documentation, which is a different mechanism. This course keeps teaching prose in Markdown; its executable files contain neither comments nor docstrings.

Worked example

python
print("Start")
if True:
    print("First line")
    print("Second line")
print("Outside the block")

Trace the result

  1. The opening print executes first, before the conditional block.
  2. Both indented print calls belong to the same if block, so both execute when its condition is True.
  3. The final print is unindented and therefore outside the block. Its position is a structural decision, not decoration.
text
Start
First line
Second line
Outside the block
Line-by-line walkthrough

Line 1: print("Start")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 2–4: if True:

Evaluate True. Execute the indented body if it is truthy; otherwise follow the alternative branch, if present. Branch order and indentation are part of the behavior.

Line 3: print("First line")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 4: print("Second line")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Line 5: print("Outside the block")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Common mistake

Mixing tabs and spaces can make visually similar lines belong to different indentation levels. Configure your editor to insert spaces.

Check your understanding

What does this program print?

python
if False:
    print("A")
print("B")
Choose one answer

Search documentation

Share this page