if, elseif and else; for loops, while loops and repeat until; tracing them by hand.
What you will learn
- Work out which branch of an if statement runs
- Count how many times a loop runs
- Choose count-controlled or condition-controlled iteration
- Complete a trace table
Selection
Selection means choosing which code runs.
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")
endiftemp ← 18
IF temp ≥ 25 THEN
OUTPUT "Hot"
ELSE IF temp ≥ 15 THEN
OUTPUT "Mild"
ELSE
OUTPUT "Cold"
ENDIFtemp = 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 >=.
Programs often get the value from the user. input("Enter the score") shows the message and gives back what the user types, as a string, so it is cast with int(...) before it is compared with a number. AQA writes this as STRING_TO_INT(USERINPUT).
The rest of this lesson and its 7 practice questions are locked.
In this lesson
- Selection
- Three kinds of loop
- Tracing loops
- Try it: Which branch runs?
7 practice questions, marked as you go; about 25 minutes in all.
Key terms
Selection, Iteration, For, Step, While, Repeat until
In this unit: Programming
Data types, operators, selection, loops, arrays, strings, subroutines, robust programs, SQL and files, read and traced step by step.