2.2.2 Programming Constructs
In this lesson, you will learn how the three basic programming constructs of sequence, selection, and iteration control the flow of a program. You will explore how instructions are carried out in order, how programs make decisions using IF and SWITCH/CASE selection, and how count-controlled and condition-controlled loops repeat instructions.
Programming Constructs
The flow of almost every program can be built using three basic programming constructs: sequence, selection, and iteration.
Sequence controls the order in which instructions are performed, selection controls which path the program follows, and iteration controls which instructions are repeated.
Sequence
Sequence means executing instructions one after another in the order in which they appear. Consider Code 1 below.
x = 5
x = x * 2
x = x + 3
print(x)The instructions run from top to bottom, as shown below in Table 1.
| Order | Instruction | Operation | Result |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
Since the final value of is 13, the program outputs 13. If the same instructions are placed in a different sequence as shown below in Code 2, however, the output will be different.
x = 5
x = x + 3
x = x * 2
print(x)As shown in Table 2 below, the output of this reordering of instructions is 16.
| Order | Instruction | Operation | Result |
|---|---|---|---|
| 1 | |||
| 2 | |||
| 3 | |||
| 4 |
This demonstrates why the sequence of instructions matters: changing their order can change the result of the program.
Selection
Selection allows a program to make a decision and follow different paths depending on whether a Boolean condition is True or False. Figure 1 below shows how selection causes a program to follow one of two paths depending on the result of a Boolean condition.
There are two forms of selection that we will explore: IF, ELSEIF, and ELSE selection, and SWITCH/CASE selection.
IF, ELSEIF, and ELSE Selection
The most common form of selection uses IF, ELSEIF, and ELSE, as shown in Code 3 below. An IF statement can contain just an IF, an IF with an ELSE, or an IF followed by one or more ELSEIF conditions and an optional ELSE.
age = input("Enter your age")
if age >= 18 then
print("Adult")
elseif age >= 13 then
print("Teenager")
else
print("Child")
endifThe conditions are checked from top to bottom. First, is evaluated. If it is True, "Adult" is output and the remaining alternatives are skipped. If it is False, the program evaluates . If this is also false, the ELSE block is executed.
ELSE does not require a condition because it acts as the final alternative. As soon as one condition evaluates to True, its block is executed and the remaining ELSEIF and ELSE alternatives are skipped.
The equivalent Python of Code 3 is shown below in Code 4. IF becomes , ELSEIF becomes , and ELSE becomes .
age = int(input("Enter your age: "))
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")The order of selection conditions matters. If a broad condition is checked too early, it may prevent a later condition from ever being reached. For example, if were checked before , an age of 20 would satisfy first and "Teenager" would be output. This is why Code 3 and Code 4 check before .
SWITCH/CASE Selection
Another way of representing selection in the OCR Exam Reference Language is a SWITCH/CASE statement. This is useful when one value is being compared against several specific possibilities. In a SWITCH/CASE structure, one expression is checked against several possible values.
switch menuChoice:
case 1:
print("Start game")
case 2:
print("Settings")
case 3:
print("Exit")
default:
print("Invalid choice")
endswitchIn Code 5 above, the value of is evaluated once. The program then compares this value with each CASE in turn. If is 1, the instructions under case 1 are carried out; if it is 2, the instructions under case 2 are carried out; and so on.
Once a matching CASE is found, the corresponding instructions are executed and the SWITCH/CASE structure is complete. If none of the listed values match, the default section is executed instead. If a default section is not included, the program simply continues with the instructions after the SWITCH/CASE structure.
Unlike an IF/ELSEIF structure, which can test conditions such as , each CASE normally represents a specific value. This makes SWITCH/CASE particularly useful for situations such as menu choices, commands, or other fixed options.
Iteration
Iteration means repeating a section of code. It is also commonly called looping. There are two main types of iteration: count-controlled iteration (which repeats a known number of times), and condition-controlled iteration (which repeats according to a Boolean condition).
Count-Controlled Iteration
A count-controlled loop is used when the number of repetitions is known in advance. The OCR Exam Reference Language uses a FOR loop as shown in Code 6 below.
for i = 1 to 5
print(i)
next iThe variable acts as the counter. On the first repetition, contains 1, so 1 is printed. Unless another STEP value (the size of each change) is specified, the counter is then automatically incremented (increased) by 1 after each repetition. The loop continues with taking the values 2, 3, 4, and 5. Once the final value of 5 has been processed, the loop ends. It therefore executes five times and outputs:
for i in range(1, 6):
print(i)In Python, the equivalent loop is shown in Code 7 above. Python’s excludes its final value, so generates the values 1 to 5.
The size of each change, or STEP, can also be controlled. In the OCR Exam Reference Language, this is shown in Code 8 below.
for i = 2 to 10 step 2
print(i)
next iThis FOR loop in Code 8 outputs:
The optional STEP value controls how much the counter changes after each repetition. A positive STEP counts upwards (as shown in Code 8 above), while a negative STEP can be used to count backwards (as shown in Code 9 below).
for i = 5 to 1 step -1
print(i)
next iThis FOR loop in Code 9 outputs:
Condition-Controlled Iteration
A condition-controlled loop repeats according to the result of a Boolean condition rather than for a predetermined number of repetitions. This means the number of repetitions depends on what happens while the program is running and may not be known in advance.
Two forms used in the OCR Exam Reference Language are WHILE and DO UNTIL loops. The key difference between WHILE and DO UNTIL is when the condition is checked.
A WHILE loop checks its condition before each repetition. It continues while the condition remains True. This is shown in Code 10 below, and its Python equivalent in Code 11.
total = 0
while total < 20
number = input("Enter a number")
total = total + number
endwhile
print("Total reached 20")The loop continues while . Once reaches or exceeds 20, the condition becomes False and execution continues after the loop.
total = 0
while total < 20:
number = int(input("Enter a number: "))
total = total + number
print("Total reached 20")Because the condition is checked before the loop body begins, a WHILE loop can execute zero times if its condition is false from the start.
On the other hand, a DO UNTIL loop checks its condition after the loop body has executed. The same task as above could be represented as shown below in Code 12.
total = 0
do
number = input("Enter a number")
total = total + number
until total >= 20
print("Total reached 20")The loop repeats until becomes true. Because the condition is checked at the end, the instructions inside a DO UNTIL loop are always executed at least once. This loop assumes the user enters values that eventually cause to reach or exceed 20. If never reaches or exceeds 20, the loop will continue indefinitely.
A condition-controlled loop must eventually reach a state where it can stop. If the variables involved in its condition are never changed appropriately, the loop may run forever. This is called an infinite loop.
Python does not provide a direct DO UNTIL statement. The same behaviour can be recreated using other programming structures, but the important concept here is to understand how a DO UNTIL loop works and how it differs from a WHILE loop.
Although both WHILE and DO UNTIL are condition-controlled loops, the position of the condition changes how they behave. This is particularly important when the condition is already satisfied before the loop begins, as summarised below in Table 3.
| Characteristic | WHILE Loop | DO UNTIL Loop |
|---|---|---|
| Condition Checked | Before the loop body | After the loop body |
| Repeats While/Until | Repeats while the condition is True | Repeats until the condition is True |
| Minimum Executions | 0 | 1 |
| Available Directly in Python | Yes | No |
