Programs with Structure
Loops inside loops
Work out how many times the body of a loop inside another loop runs, and in what order the two counters change.
A loop is just a block of lines, and a block of lines can hold a loop, so a loop can sit inside a loop. Nothing new is added to the language to make this work — it falls out of what indentation already meant. What is new is the behaviour, and it catches people out: the inner loop runs through its whole range from beginning to end every single time the outer loop goes round once. The inner counter therefore races through all its values, resets, and races through them again, while the outer counter moves on by one.
Multiply, do not add
Because the inner loop starts again from scratch on every trip of the outer one, the deepest line runs the outer count times the inner count — not the outer plus the inner. Adding them is the mistake worth guarding against, because it gives an answer that looks reasonable and is far too small. The same reasoning tells you which counter moves faster: the inner one changes on every single trip through the deepest line, while the outer one holds still until the inner loop has finished with all of its values.
Worked example
An outer loop over range(1, 4) holds an inner loop over range(1, 3), and the inner loop holds one line that prints both counters. What happens?
The outer counter takes 1, and the inner loop starts. It takes 1, then 2, and then it is finished.
The inner loop is complete before the outer counter has changed at all. Everything that happens with 1 as the outer value happens before anything else.
Try it together
Now count the lines of this one together. An outer loop over range(1, 5) holds two things: a line printing the outer counter, and then an inner loop over range(1, 4) whose one line prints the inner counter.
Take the two printing lines separately, and only put them together at the end.
1.How many times does the line printing the outer counter run?
Have a go
Have a go on your own. A loop over range(2, 5) holds a loop over range(1, 6), which holds one line. How many times does that line run?
Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.