Programs with Structure
Blocks and indentation
Read a program's indentation to say which lines belong to which block, and how often each line runs.
In this language the indentation is not decoration and it is not a matter of taste — it is the punctuation, and it is the only punctuation there is for this job. A line that ends in a colon is a heading, and the lines pushed in underneath it are its block: the thing that runs when the heading says so. The block ends at the first line brought back out to the left, and that line is not part of it. Blocks can sit inside blocks, each pushed in a little further than the one holding it, and moving a single line left or right by four spaces changes what a program does without changing a word of it.
Two questions, in this order
Faced with any line at all, ask two things and ask them in this order. First, which block is this line in? That is settled entirely by how far in it is pushed and by what heading sits above it, and by nothing else. Second, how many times does that block run? A line in no block at all runs once. A line inside a loop runs once per trip round. A line inside a block inside a loop runs once per trip, but only on the trips where the inner heading lets it. Answering these the other way round is what makes tracing feel impossible; answering them in order makes it mechanical.
Worked example
A program has four lines. First, total = 0 on the left margin. Then a loop heading, for n in range(2, 7):, also on the left margin. Then total = total + 2, indented under the loop. Finally print(total), brought back out to the left margin. What does it print?
Sort the lines into blocks first. The adding line is the only one indented, so the loop's block holds that line and nothing else.
Doing this before any arithmetic is what stops the two hard parts happening at once.
Try it together
Now work through this one together. On the left margin: count = 0, then the heading for n in range(1, 5):. Indented under the heading: count = count + 1. Then, back out on the left margin: print(count).
Take the two questions from the rule in order, one line at a time.
1.How many times does the line adding 1 to count run?
Have a go
Have a go on your own. A program reads: for n in range(1, 3): with print(n) indented under it, and then print(50) brought back out to the left margin. How many numbers does it print?
Ready to practice?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.