Menu

Writing and Refining Algorithms

Nesting

Nesting means placing one programming construct inside another. For instance, an if statement can be written as part of a loop body, one loop can be placed within another loop, or an if statement can sit inside a second if statement. The inner construct belongs to the outer one, and in Python the indentation shows this: the inner block is written further to the right.

When a loop is nested inside another loop, the outer loop controls the main passes. On each pass, the inner loop starts again and runs all the way to its end. The outer loop does not move on until the inner loop has finished. In the same way, an if placed inside a loop is tested on every pass, so each value can be checked and acted on separately.

A worked example

This program prints a label for every player in three teams. The outer loop chooses the team and the inner loop chooses the player.

for team in range(1, 4):
    for player in range(1, 3):
        print("Team " + str(team) + ", player " + str(player))

Output:

Team 1, player 1
Team 1, player 2
Team 2, player 1
Team 2, player 2
Team 3, player 1
Team 3, player 2
Outer loop passInner loop runsLabels printed
team = 1player = 1, then player = 22
team = 2player = 1, then player = 22
team = 3player = 1, then player = 22

The inner loop runs twice for each of the three outer passes, so the printing line runs 3 × 2 = 6 times. In general, if the outer loop runs m times and the inner loop runs n times for each outer pass, the inner block runs m × n times.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms