Computer Science · Ch 6 — Flow of Control
Indentation
6.3
Indentation
How does Python know which statements belong to the if block and which come after it? Most programming languages answer this by wrapping the statements of a block inside curly brackets. Python takes a different route: it uses indentation — for ordinary blocks and for nested block structures alike.
What indentation means
Indentation is the leading whitespace (spaces and tabs) at the beginning of a statement. In Python, statements written at the same level of indentation are grouped together into a single block of code. Indentation is not decoration — it is the block structure.
Key points to remember:
- The Python interpreter checks indentation levels very strictly and raises a syntax error whenever indentation is incorrect or inconsistent.
- It is common practice to use one tab per level of indentation (deeper nesting simply adds another level).
- In an
if..elsestatement there are two blocks of statements, and the statements inside each block must be indented by the same amount of spaces or tabs.
Blocks in action
# Find the larger of two pre-specified numbers
p = 5
q = 6
if p > q:
# Block 1 — runs only when the condition is true
print("first number is larger")
print("Bye")
else:
# Block 2 — runs only when the condition is false
print("second number is larger")
print("Bye Bye")
second number is larger
Bye Bye
``` …