Menu

Writing and Refining Algorithms

Indentation

In Python, indentation is the spaces at the start of a line, and it is part of the language rather than decoration. Every if, elif, else, for and while line ends with a colon, and the indented lines underneath form the block that runs.

The colon starts a block

Python sees the colon at the end of the line and expects the next line to be indented. The indented lines belong to that construct. Any line that is not indented is outside the block, so the block ends where the indentation goes back to the left.

points = 0
for lap in range(1, 4):
    score = int(input("Score: "))
    if score > 5:
        print("Bonus lap")
        points = points + score
print(points)

Output when the user types 7, 2, 9:

Score: 7
Bonus lap
Score: 2
Score: 9
Bonus lap
16

Nested boxes showing the IF and ELSE blocks of the museum program and the loop body with its nested IF block in the spelling program, with the final print statements outside the boxes.

Nesting adds another level

When one construct sits inside another, the inner block is indented further than the outer one. In the program, the lines inside the for loop are indented once, and the two lines inside the if are indented twice. That extra level shows Python which lines belong to the if and which belong only to the loop.

Coming back to the left

The final print(points) is not indented, so it is not inside the loop. It runs once, after every lap has been processed. If it were indented to match the loop's block, it would run after every lap instead. Indentation is how you show which lines are inside which construct.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms