Menu

Pseudocode

Indentation and Block Structure

Indentation is the space at the start of a line that shows which statements sit inside a selection or a loop. A clear block structure groups those statements together, so you can see at a glance what runs only when a condition is true or while a loop repeats.

Selections

In a selection, the IF block is the set of statements that run when the condition is true. Indenting them under the IF shows they belong to it. A statement written back at the same level as the IF is outside the block, so it runs whether the condition was true or false.

answer = input("Is the museum open today? (yes/no): ")
if answer == "yes":
    print("Book your tickets online")
    print("Doors open at 10am")
else:
    print("Try again next week")
print("Thanks for checking")

Output when the user types yes:

Is the museum open today? (yes/no): yes
Book your tickets online
Doors open at 10am
Thanks for checking

The two print() statements are indented under the if, so they only run when the answer is "yes". The else branch has its own indented block. The last print() sits back at the left margin, outside the selection, so it runs whichever answer was typed. Every statement in the same block lines up, because Python uses the indentation to work out which statements belong together.

Loops

Inside a loop, the repeated statements form the loop body. Indenting the body under the loop header shows exactly what repeats, and a statement after the loop, back at the left margin, runs once when the loop has finished. That makes it easier to trace how many times each line runs.

passed = 0
for number in range(1, 6):
    score = int(input("Spelling score for word " + str(number) + ": "))
    if score >= 8:
        passed = passed + 1
print("Words passed: " + str(passed))

Output when the user types 9, 7, 10, 8, 6:

Spelling score for word 1: 9
Spelling score for word 2: 7
Spelling score for word 3: 10
Spelling score for word 4: 8
Spelling score for word 5: 6
Words passed: 3

The lines indented under the for repeat once for each of the five words, and the line that adds to passed is indented again because it only runs when the score is 8 or more. The final print() is not indented, so it runs once, after the loop has ended.

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.

Indentation is not decoration: it is part of how the block structure shows the algorithm's logic. In Python, a block whose lines do not line up stops the program with an IndentationError.

Practise this