Logical Blocks and Indentation
Indentation represents control structure in Python. A one-line change in indentation can decide whether work happens once or repeatedly.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Read the owner of a block
A loop header introduces a suite. Each directly indented line in that suite belongs to the loop body. A conditional inside the suite can introduce a further nested block. Identify the enclosing decision for each statement before following a complicated trace.
Print the result at the intended time
A total starts at zero. A loop processes 2, 5, and 1 and adds each number. Printing directly after the addition inside the body emits 2, then 7, then 8. Moving the print to the outer indentation emits only 8. With an empty list the former emits nothing and the latter emits zero. Track those two cases when checking program output and state.[1][2]
Mark the operation's owner on each line
Here a loop computes a total and checks whether any individual order is large. The output needs to be emitted once, even when there are no orders. Indentation records what belongs under the loop and what happens afterward.
amounts = [3, 12, 4]
total = 0
large = 0
for amount in amounts:
total += amount
if amount >= 10:
large += 1
print(total, large)
The total is nineteen and the large count is one. The inner increment runs only for twelve. The final print is not part of the loop, so it runs exactly once. If you place it under the loop after the conditional, three separate pairs are printed. If it is moved under the conditional, only the matching iteration prints. Predict which of those outputs you would get on an empty sequence. See branch execution and output as an effect for the two decisions.
Use a trace when editing indentation
Mark each statement as initialization, iteration, branch body, or finalization. This reveals common mistakes such as resetting the total on each pass or finalizing only when a branch was true. In languages using braces, the same tracing method follows braces and control keywords instead of indentation alone.
A formatter can make conventional spacing consistent. It cannot infer which branch is meant to own a line when both arrangements are syntactically valid. A test with no inputs, two matching inputs, and mixed inputs exposes the difference. Off-by-one and small loop cases are useful for similar errors around the first and last step.