Learn
B2.3.1 | INSTRUCTION SEQUENCE
01 | THE RIGHT ACTION AT THE WRONG TIME
A program can contain the correct calculation, input and output statements and still fail because they occur in the wrong order. Printing a total before calculating it is like handing out a receipt before knowing what was bought.
A sequence is the order in which instructions execute. A correct sequence respects dependencies: obtain information before using it, establish valid state before changing it, and report a result after the required operation succeeds.
This common SL/HL lesson develops complete Python programs and traces instruction order. It also covers incorrect output, infinite loops and deadlock, including why those failures require different explanations.
02 | BEGIN WITH AN OBJECTIVE
Suppose the objective is: receive a valid whole-number ticket count, charge 4.50 per ticket, apply a ten-percent discount to the subtotal and display the discounted total to two decimal places.
The objective determines the necessary dependencies. The ticket count must exist before its subtotal can be calculated; the subtotal must exist before its discount; both values must exist before the final total.
Write down the expected result for a small example. Three tickets give subtotal 13.50, discount 1.35 and final total 12.15. This lets you judge the sequence rather than merely check that the program runs.
03 | INPUT, PROCESS, OUTPUT
raw = input("Tickets: ")
tickets = int(raw)
subtotal = tickets * 4.50
discount = subtotal * 0.10
total = subtotal - discount
print(f"{total:.2f}")
The program follows input → conversion → calculation → output. Assume valid numeric input in this first version. input supplies text; int produces the integer used by multiplication.
The f-string formats the final number to two places. Formatting changes presentation, not the underlying approximate binary floating-point representation. These are small teaching values, not a complete financial calculation policy.
The statement order is not arbitrary: later expressions require values produced earlier. We will add validation and safe failure routes after understanding the successful path.
04 | ASSIGNMENT READS THE RIGHT SIDE FIRST
total = 10
new_value = 4
total = total + new_value
print(total) # 14
Evaluate total + new_value using the current values 10 and 4, then store 14 in total. The old total is read before that name is rebound.
Changing the order can change the inputs to the calculation. If total = 0 executes immediately before the update, the result becomes 4 rather than 14.
A sequence is a series of state changes. Trace what each name holds at the moment an expression reads it, rather than relying on the value it had earlier or will have later.
05 | A DEPENDENCY MAP
| Instruction | Needs beforehand | Produces or does |
|---|---|---|
| raw = input(...) | An input source | Text value raw |
| tickets = int(raw) | Suitable raw text | Integer tickets |
| subtotal = tickets * 4.50 | tickets | subtotal |
| discount = subtotal * 0.10 | subtotal | discount |
| total = subtotal - discount | subtotal and discount | total |
| print(f"{total:.2f}") | total | Formatted output |
Independent instructions can sometimes be reordered without changing required behaviour. The point is to satisfy dependencies and observable effects, not to memorise one universal line order for every program.
In this particular six-line example, the chain of dependencies requires the displayed order. An assignment to an unrelated configuration name could have more than one valid placement.
06 | READING BEFORE ASSIGNMENT
# Incorrect: tickets has not been assigned.
subtotal = tickets * 4.50
tickets = 3
In a fresh module, this raises NameError at the first line. The later assignment does not travel backwards in time to make the earlier read valid.
Inside a function, a local read before a local assignment can instead produce UnboundLocalError. The precise exception depends on the scope and operation.
Interactive environments can hide this bug if a name remains from an earlier run. Test from a clean state as well as from a convenient existing session.
07 | INCORRECT OUTPUT WITHOUT AN EXCEPTION
total = 0
print(total)
total = 12.15
This program validly prints 0. It then assigns 12.15, but does not print again. No exception is needed for the output to violate the objective.
Move the output after the required calculation. Do not claim that a later assignment automatically changes text already printed.
Check output order too. A prompt should appear before the relevant input; a success confirmation should follow an operation that actually succeeded.
08 | ORDER CAN CHANGE AN ARITHMETIC RESULT
subtotal = 100.0
subtotal = subtotal * 0.90
subtotal = subtotal + 5.0
print(subtotal) # 95.0
This discounts 100 to 90, then adds a fixed charge of 5, giving 95. If the charge is added first and the ten-percent discount is then applied to 105, the result is 94.5.
Neither sequence is universally correct. The specification must say whether the charge is included in the discounted amount. A difference in outputs is evidence of different rules, not automatically evidence that one arithmetic operator is broken.
Keep named intermediate values when they make the intended order clearer.
09 | INTERACTIVE: CONSTRUCT THE SIX-LINE PROGRAM
Arrange the ticket program using the up/down controls, then check and trace it. The input is assumed to be a valid whole number from 0 to 20. The activity executes only the supplied statements; it is not an arbitrary Python interpreter.
Identify the first read whose required value does not yet exist. A correct result includes a trace of the named values and the final output. Moving a statement clears the old feedback.
10 | SEQUENCE INSIDE FUNCTIONS
def final_cost(tickets):
subtotal = tickets * 4.50
discount = subtotal * 0.10
total = subtotal - discount
return total
answer = final_cost(3)
print(f"{answer:.2f}")
The definition creates the function. Its body executes on the call final_cost(3). The caller waits for the returned value, binds it to answer and then prints it.
Returning before a necessary calculation prevents the later statements in that call from being reached. Printing inside a function is not a substitute for returning a result the caller needs.
Define a function before an execution path calls it. A function may refer to another name that is established later in source order, provided it exists when that reference actually executes; follow runtime order rather than assuming every definition immediately runs its body.
11 | VALIDATE BEFORE THE DEPENDENT OPERATION
raw = "3"
try:
tickets = int(raw)
except ValueError:
print("Enter a whole number")
else:
if 0 <= tickets <= 20:
total = tickets * 4.50 * 0.90
print(f"{total:.2f}")
else:
print("Tickets must be from 0 to 20")
Invalid numeric text follows the handler rather than reaching multiplication with an unassigned tickets value. A converted integer still needs the required range check before processing.
If validation is performed only after a booking is saved or a payment request is sent, it may be too late to prevent the unwanted effect. Order checks before consequential operations.
Exception handling can support the intended routes, but it does not repair a wrong discount rule.
12 | KEEP SUCCESS OUTPUT ON THE SUCCESS PATH
Imagine a save operation fails because a resource is unavailable. Printing “Saved” after an unconditional handler would mislead the user if the failed path still reaches it.
Place success output after confirmed success, or use a control structure that returns or branches appropriately on failure. The handler should report the actual outcome.
The same principle applies to jobs: removing a job from a queue is not proof it completed, and starting a file write is not proof every required record was stored. Define the operation’s success condition.
13 | INITIALISE ONCE OR RESTART DELIBERATELY?
values = [4, 7, 2]
total = 0
for number in values:
total = total + number
print(total) # 13
total begins before the loop so each iteration preserves earlier contributions. Moving total = 0 inside the loop would reset the accumulated value before every addition.
For a 2D row-total task, resetting row_total inside the outer row loop is intentional, while a grand_total remains outside it. Initialisation placement follows the variable’s purpose.
A correct statement can therefore be in the wrong region even if it appears before the line that uses it.
14 | INFINITE LOOPS: NO ROUTE TO THE EXIT
count = 1
while count <= 3:
print(count)
count = count + 1
This loop outputs 1,2,3 and exits after count becomes 4. The continuation test is evaluated again using the updated value.
If the increment is removed, count stays 1 and the condition remains true. That gives an infinite run for this initial state. The missing state change explains the failure.
Not every intentionally ongoing event loop is a bug, but a task required to finish needs a justified exit path or an appropriate interruption policy.
15 | AN UPDATE CAN EXIST BUT NEVER BE REACHED
count = 1
while count <= 3:
if count == 2:
count = count + 1
continue
print(count)
count = count + 1
This version prints 1 and 3, skips output for 2 and still terminates. The skip branch increments before continue, while the normal branch increments at the end.
If continue comes before the increment in that skip branch, the increment is unreachable. When count reaches 2, it repeatedly takes that branch without changing count.
Avoid the problem by arranging an update on every continuing route, or by using a counted loop where its iteration mechanism suits the task. Simply spotting an increment somewhere in the source is not enough.
16 | WAITING FOR INPUT IS NOT AUTOMATICALLY AN INFINITE LOOP
A program paused at input may be waiting for a person. A program blocked on a resource may be waiting for another task. A loop repeatedly executing with an unchanged true condition is a different behaviour.
Inspect where execution is paused and what event could let it proceed. A user supplying input may resolve a legitimate wait; it cannot fix a missing count increment inside a tight loop.
Timeouts and cancellation can help some external waits, but they require a defined response. A timeout alone does not prove that every resource was released or that retry is safe.
17 | DEADLOCK: TASKS WAIT ON EACH OTHER
A deadlock can occur when tasks hold resources while waiting in a cycle for resources held by one another. This is different from a single loop repeatedly computing.
Suppose Task A holds a printer lock and needs a scanner lock. Task B holds the scanner lock and needs the printer lock. Neither releases its held lock until it obtains the other. Each is waiting for the other task to move first.
A lock controls access to a shared resource or critical section. The example is about software resource ownership; it does not claim physical devices necessarily expose exactly these locks.
18 | THE ORDER THAT CREATES A CIRCULAR WAIT
| Step | Task A | Task B | Consequence |
|---|---|---|---|
| 1 | Acquire printer lock | Not yet running | Printer held by A. |
| 2 | Still holds printer | Acquire scanner lock | Scanner held by B. |
| 3 | Request scanner; wait | Still holds scanner | A waits for B. |
| 4 | Still waiting | Request printer; wait | B waits for A; circular wait. |
Each task’s individual plan might look plausible: get one resource, then the other, then work. The interaction creates the failure because resources are acquired in opposite orders.
Deadlock requires the waiting conditions in the model. Two tasks merely running slowly, or one task waiting while its owner can finish and release, is not by itself evidence of deadlock.
19 | A CONSISTENT RESOURCE ORDER CAN PREVENT THIS CYCLE
Require both tasks to acquire printer before scanner. If A holds printer, B waits for printer without holding scanner. A can then obtain scanner, complete its work and release both resources. B can proceed afterwards.
A consistent global ordering prevents circular wait among the locks governed by that ordering. All relevant tasks must follow it; unrelated locks or a different dependency can create other problems.
Use appropriate resource cleanup even when work fails, and avoid unnecessary resource holding. Acquisition policies, bounded waits and recovery designs require context; one corrected two-lock example is not a universal guarantee that concurrent software cannot deadlock.
20 | INTERACTIVE: COMPARE TWO LOCK ORDERINGS
Step through a specified two-task schedule. The unsafe schedule gives the tasks opposite resource orders. The safe schedule gives both printer-then-scanner order. This is a model of lock ownership and waiting, not an actual concurrent hardware operation.
At each pause, say who owns each lock and whether a waiting task can be unblocked by an owner that is still able to proceed. The final unsafe state has no next successful step under its stated rules.
21 | DISTINGUISH THE FAILURE MODES
| Behaviour | Example | Investigation / response |
|---|---|---|
| Incorrect output | Print before the correct assignment. | Trace dependencies and move output to the required route. |
| Infinite loop | Every continuing route skips the needed update. | Inspect state changes and exit conditions. |
| Deadlock | A holds printer and waits for scanner; B holds scanner and waits for printer. | Inspect ownership/wait cycles and coordinate acquisition order. |
| Legitimate wait | A task waits while another can finish and release its resource. | Check the owner’s progress and the expected wake-up event. |
Do not diagnose all non-response as “an infinite loop”. The relevant evidence may be changing variables, a blocked input, call stacks, lock ownership or an unavailable external service.
22 | CONSTRUCT A COMPLETE ORDERED SOLUTION
A workshop has 12 available places and charges 4.50 per place. Given text for a requested quantity, construct a program that converts and validates it, checks sufficient places, calculates cost, updates remaining places and only then confirms the accepted booking. Reject invalid or excessive requests without reducing availability.
For this small model, requests are processed one at a time and data is in memory. No payment or persistent save is attempted. A real multi-user booking service needs suitable coordination and transaction/error handling.
Reveal one possible solution
def book_places(raw, available):
try:
requested = int(raw)
except ValueError:
return available, "Enter a whole number"
if requested <= 0:
return available, "Request must be positive"
if requested > available:
return available, "Not enough places"
cost = requested * 4.50
remaining = available - requested
return remaining, f"Accepted: {requested}; cost {cost:.2f}"
available, message = book_places("3", 12)
print(message)
print("Remaining:", available)
The result is Accepted: 3; cost 13.50, followed by Remaining: 9. Every rejected route returns unchanged availability. Multiple return values are unpacked into the two names at the call site.
23 | TEST ORDER, STATE AND OUTPUT
| Test | Expected evidence |
|---|---|
| Ticket input3 | Subtotal13.50, discount1.35, total/output12.15. |
| Invalid numeric text | Conversion response; no successful result based on an unassigned value. |
| Booking3 from12 | Acceptance and remaining9. |
| Booking13 from12 | Rejection and remaining12. |
| Loop count1 to3 | Outputs1,2,3 and terminates. |
| Skip count2 branch | State still advances; no endless repeat at2. |
| Opposite two-lock ordering | Demonstrable circular wait under the stated schedule. |
| Common two-lock ordering | Owner can finish/release and waiting task can proceed. |
Use clean initial state and inspect intermediate values. A final total can accidentally match while output timing, resource ownership or a rejected-path update is still wrong.
24 | A CONSTRUCT ANSWER NEEDS CODE
Produce a program meeting the objective, not only an account of sequence. Make initialisation, input/conversion, validation, calculation, state changes and output clear. Use indentation to identify the paths.
Explain assumptions when a task leaves concurrency, input validity or failure policy unspecified. Do not present a classroom sequential model as a fully coordinated production system.
Trace at least one successful and one rejected case before judging your sequence.
25 | COMMON MISTAKES
Do not read a name before the path assigns it, reset a total at the wrong loop level, print stale state, skip an essential update with continue or confirm success after a failed operation.
For resource use, do not acquire the same set of locks in inconsistent orders across cooperating tasks. Release what was acquired appropriately; unexpected failure must not silently leave shared resources held.
Avoid fixing an example by hardcoding its expected output or hiding every exception. Correct the dependency or control-flow cause, then retest.
26 | READY FOR SELECTION AND REPETITION
You can now connect instruction order to data dependencies, observable output, termination and resource waiting. These ideas apply inside branches, loops and functions as well as in a short straight-line program.
The next lesson constructs selection structures, where conditions choose which sequence executes.