AQA GCSE Computer Science (8525), section 3.2.2 (Programming concepts)
What is selection?
Selection lets a program choose which statements to run, depending on whether a condition is true or false. It is one of the three basic building blocks of programs, with sequence (steps in order) and iteration (repeating).
IF statement
IF age >= 18 THEN
OUTPUT "You can vote"
ENDIF
IF ... ELSE
IF age >= 18 THEN
OUTPUT "Adult"
ELSE
OUTPUT "Child"
ENDIF
IF ... ELSE IF ... ELSE
Use this when there are more than two outcomes. The conditions are checked in order, and only the first true one is run.
IF mark >= 80 THEN
grade ← "A"
ELSE IF mark >= 60 THEN
grade ← "B"
ELSE IF mark >= 40 THEN
grade ← "C"
ELSE
grade ← "U"
ENDIF
Python
mark = 65
if mark >= 80:
grade = "A"
elif mark >= 60:
grade = "B"
elif mark >= 40:
grade = "C"
else:
grade = "U"
print(grade) # B
Things to remember
- The condition is either true or false (a Boolean value).
- Indent the statements inside each branch so the structure is clear.
- Put the most demanding condition first. If
mark >= 40came first, a mark of 90 would get a C. - The final
ELSEcatches everything else.
Common mistake: putting the conditions in the wrong order. With IF mark >= 40 first, every pass mark gets the same grade. Also, a single = is assignment in many languages: for a comparison use == (Python) or = in pseudo-code conditions.
Exam tip: when you write selection, indent and close each IF with ENDIF. Test your answer by trying a value on each boundary, such as 80, 79, 60 and 59.
Check yourself
What are the three basic programming constructs?
Sequence, selection and iteration.
What grade does a mark of 60 get in the example above?
B, because 60 >= 60 is true and 60 >= 80 is false.
When is the ELSE part of an IF statement run?
When none of the earlier conditions is true.