2.2.1 - Sequence, selection and iteration

2.2.1 - Sequence, selection and iteration

A program becomes useful when its instructions can choose and repeat actions as well as execute them in order. You will combine these constructs, trace their changing state and recognise the differences between OCR pseudocode and Python. Small boundary cases will help you find errors that an ordinary run can hide.

Sequence changes program state

Sequence executes instructions in their stated order, so an earlier assignment can change what a later instruction reads. A variable is a named place for a value; the collection of current values is the program's state. Assignment replaces a value. Equality tests whether two values are equal.

In OCR pseudocode, = assigns and == compares. A variable is declared on first assignment and takes the type of its value. Python also uses = and ==, but its names are bound to objects. These distinctions matter when translating an algorithm rather than copying its punctuation.

OCR prints a consistent pseudocode style so that you can read its algorithms. You do not need to memorise the exact syntax: your own pseudocode answers may use any style whose meaning a competent programmer can reasonably infer. Clear conditions, bounds and indentation communicate the logic.

Pseudocode
boxes = 4
boxes = boxes + 2
cost = boxes * 3
print(str(cost))

The right side of boxes = boxes + 2 uses the old value 4, then assigns 6. cost becomes 18. Swapping the second and third instructions would calculate 12 instead: the same statements in a different sequence have different effects.

Input commonly arrives as text. int("12") converts suitable integer text to 12, float("2.5") converts to 2.5, and str(12) produces text for concatenation. A cast is not validation: Python int("twelve") fails rather than guessing a number. Specify the allowed input or check it before conversion.

Python
minutes = int(input("Minutes: "))
hours = minutes // 60
remainder = minutes % 60
print(str(hours) + "h " + str(remainder) + "m")

For input 135, the quotient is 2 and remainder is 15. OCR DIV maps to Python // for these non-negative integer examples; MOD maps to %. Both use / for division, but Python / produces a floating-point result. OCR exponentiation ^ maps to Python **; Python ^ is a different, bitwise operation. Parentheses make intended order explicit. The examples here use non-negative integers, avoiding differing conventions for negative remainders.

Selection chooses a branch

Selection, also called branching, chooses instructions according to a Boolean condition. A comparison such as temperature < 0 has a true or false result; AND, OR and NOT combine or reverse conditions. Python spells these and, or and not.

Pseudocode
if temperature < 0 then
    print("Ice risk")
elseif temperature <= 5 then
    print("Cold")
else
    print("Mild")
endif

Only the first true branch in this chain executes. At 0 the first test is false and the second true, giving Cold; at 5 it is still Cold; at 6 both tests are false, giving Mild. The order deliberately tests the narrower category first. Two separate if statements could both execute, unlike this mutually exclusive chain.

A range check age >= 12 AND age <= 17 requires both bounds. Using OR would accept every age: a value below 12 is still at most 17, while a value above 17 is still at least 12. Boundary tests expose that mistake.

OCR also uses switch/case to compare one expression against alternatives:

Pseudocode
switch service:
    case "S":
        charge = 2
    case "E":
        charge = 5
    default:
        charge = -1
endswitch

The matching case executes; the default handles an unmatched service. This is suitable for discrete choices, whereas an if/elseif chain naturally handles ranges. A faithful Python translation here is if service == "S":, elif service == "E":, and else:, with the corresponding assignments indented underneath. Do not import a different language's case fall-through rules into this OCR example.

Iteration depends on bounds and timing

Iteration repeats a body of instructions. A count-controlled loop uses a known sequence of values; a condition-controlled loop repeats according to a test. Correctness depends on which values are included and when the test occurs.

Pseudocode
total = 0
for i = 2 to 4
    total = total + i
next i

OCR's upper bound is inclusive: the body uses 2, 3 and 4. The totals after the three iterations are 2, 5 and 9. Python range(2, 5) gives these values because its stop value is excluded; range(2, 4) would omit 4.

A pre-test loop such as while tests before executing its body and can execute zero times. With count = 0, while count < 3, and count = count + 1 in the body, the values after the body are 1, 2, 3. The final failed test prevents a fourth iteration. Forgetting the update would leave the condition true forever.

OCR do ... until is a post-test loop: the body executes before the condition is tested. It executes at least once and stops when the until condition becomes true.

Pseudocode
do
    choice = input("Enter S or E: ")
until choice == "S" OR choice == "E"

For entries X, E, two inputs are read. Python has no directly equivalent do/until statement; one explicit translation is:

Python
while True:
    choice = input("Enter S or E: ")
    if choice == "S" or choice == "E":
        break

break exits this loop on the stopping condition. A pre-test alternative reads once before a while choice != "S" and choice != "E": loop, then reads again inside it. Simply writing while choice == "S" or choice == "E" reverses the intended continuation condition and may use a value before input has assigned it.

OCR's count-loop end is included; Python's range stop is excluded. A while condition permits another pass when true; an until condition ends repetition when true.

The sandbox below explores zero and one pass with a different program. Make each prediction before running; its final count and the loop-variable lifetime reveal different boundary behaviours.

Change the number of visits

{"exercise_id":"h446-study-loop-visits","task_version":"1","runtime_profile":"python-console-v1","original_filename":"loop_visits.py","file_mode":"fresh","code":"limit = 4\ncount = 0\nfor position in range(limit):\n count = count + 1\n print("visit", position)\nprint("count", count)\n","instructions":"Ungraded exploration. Assume limit is a non-negative integer. Predict the lines for limit=4, then run. Change limit to 0 and 1: predict before each run and explain why the final count still exists. Finally move the visit print outside the loop and try limit=0; observe the unassigned loop name, then restore the print inside the loop."}

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account