Selection

An if statement chooses which code runs. The conditions are checked from the top; the first true one runs and the rest are skipped.

temp = 18
if temp >= 25 then
    print("Hot")
elseif temp >= 15 then
    print("Mild")
else
    print("Cold")
endif
temp ← 18
IF temp ≥ 25 THEN
    OUTPUT "Hot"
ELSE IF temp ≥ 15 THEN
    OUTPUT "Mild"
ELSE
    OUTPUT "Cold"
ENDIF
temp = 18
if temp >= 25:
    print("Hot")
elif temp >= 15:
    print("Mild")
else:
    print("Cold")

This prints Mild: 18 >= 25 is false, 18 >= 15 is true, so it stops there. Watch >= against >: a value exactly on the boundary counts with >=.

Three kinds of loop

  • Count-controlled: a for loop runs a set number of times. for i = 1 to 5 runs with i = 1, 2, 3, 4, 5: both ends included. In Python, range(1, 6) stops before 6.
  • Condition-controlled, checked first: a while loop checks its condition before each pass, so it might not run at all.
  • Condition-controlled, checked last: repeat until (OCR: do ... until) runs its body, then checks, so it always runs at least once. Python has no repeat loop; it uses while True: with a break.

A loop that keeps halving

n = 100
count = 0
while n > 1
    n = n DIV 2
    count = count + 1
endwhile
print(count)
n ← 100
count ← 0
WHILE n > 1
    n ← n DIV 2
    count ← count + 1
ENDWHILE
OUTPUT count
n = 100
count = 0
while n > 1:
    n = n // 2
    count = count + 1
print(count)

Tracing loops

To trace a loop, keep a row for each pass and write every variable's value at the end of that pass. Check the condition with the current values before (while) or after (repeat until) each pass.

For the halving loop above: n goes 50, 25, 12, 6, 3, 1 and count goes 1 to 6. When n is 1, n > 1 is false, so it outputs 6.

Practise in Python: if and else, for loops and while loops.

Which branch runs?

Check each condition in order with the value entered.