Menu

Writing and Refining Algorithms

If, elif and else

if, elif and else let an algorithm choose between different paths. The if condition is tested first. An elif condition is tested only when every condition above it was false, and the else branch runs only when no condition matched. As soon as one condition is true, its branch runs and the remaining checks are skipped, so only one branch runs.

The checks are made from top to bottom, so the first true condition wins even if a later condition would also be true. An else has no condition of its own: it is the fallback that catches every case not caught earlier.

For example, this program decides what to do based on the moisture of a plant's soil. It reads a whole number and tests it in order.

moisture = int(input("Soil moisture %: "))
if moisture < 30:
    print("Water the plant")
elif moisture < 60:
    print("Check again tomorrow")
else:
    print("Do not water")

Output when the user types 45:

Soil moisture %: 45
Check again tomorrow

If the moisture is 20, the first condition is true, so the plant is watered and the elif and else are skipped. If it is 45, the first condition is false, the elif is checked and matches, and the else is skipped. If it is 80, both tests are false, so the else branch runs. The keyword is written as elif, not as two words.

Practise this

OCR GCSE Computer Science · Writing and Refining Algorithms