Writing and Refining Algorithms
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.
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
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.
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.
OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Selection
OCR GCSE Computer Science · Count-Controlled Iteration
OCR GCSE Computer Science · Defensive Design