B2.3.1 Getting the order of instructions right
SL + HLCommand term: Construct1. Same lines, different order, different result
Both programs contain exactly the same five statements. Step through them side by side: the computer obeys the order, not your intention.
2. Put the instructions in order
Drag the lines (or use Up and Down) into an order that meets the objective, then Run. Your program really executes: a wrong order gives the wrong output, or an error.
3. Infinite-loop detector
Each loop is supposed to stop. Run it: the simulator gives up after 40 passes, as you would press Ctrl+C. Watch the loop variable, find why it never stops, and choose a fix that still meets the objective.
4. Deadlock simulator
Two ShelfWise programs both need catalogue.csv and loans.csv, and each file can be locked by only one program at a time. Choose a strategy and step through. Solid arrows: holds. Dashed arrows: waiting for.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Diagnose the problem
Wrong order, infinite loop, deadlock, or no error? Streaks of 3+ score double.
7. 45-second speed round: does it stop?
A new loop each time. Will it terminate, or run forever?
checkout, and make both loops terminate.Expected output
Think about it
(1) In run_commands, why must i < len(commands) come before commands[i] != "quit" in the condition? (Try swapping them with the second test.) (2) What would a librarian see if the loan were recorded before the availability check?
Check my code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Put the lines in order
These shuffled lines (a Parsons problem) should ask for a password until the user types "shelf", allowing 3 attempts. Put them in the correct order with correct indentation:
print("access granted")
attempts = 0
while attempts < 3:
else:
if guess == "shelf":
print("locked out")
break
guess = input("password: ")
attempts += 1 To test without typing, the version below reads guesses from a list.Starter file (write your code where it says pass # your code here):
def login(guesses):
pass # your code here
# ---- tests ----
login(["abc", "shelf", "x"])
login(["a", "b", "c"])
Expected output when your code is correct:
access granted locked out
Hint
Model solution
Order: attempts = 0; while attempts < 3:; (indented) guess = input(...), attempts += 1, if guess == "shelf":, (indented twice) print("access granted"), break; then else: at the same level as while, with print("locked out") inside. A while ... else runs the else only when the loop ends without break.
def login(guesses):
attempts = 0
while attempts < 3:
guess = guesses[attempts]
attempts += 1
if guess == "shelf":
print("access granted")
break
else:
print("locked out")
# ---- tests ----
login(["abc", "shelf", "x"])
login(["a", "b", "c"])
Task 2: Order of operations changes the answer
A savings account adds 2% interest at the end of each month, after the monthly deposit. Write balance_after(months, deposit) in the correct order. Then write wrong_order that adds interest before the deposit, and print both for 12 months of 100. Explain the difference.
Starter file (write your code where it says pass # your code here):
def balance_after(months, deposit):
pass # your code here
def wrong_order(months, deposit):
pass # your code here
# ---- tests ----
print(balance_after(12, 100))
print(wrong_order(12, 100))
Expected output when your code is correct:
1368.03 1341.21
Hint
Model solution
In the wrong order, each deposit waits one extra month before earning interest, so the final balance is lower. Same statements, different sequence, different result.
def balance_after(months, deposit):
balance = 0
for _ in range(months):
balance += deposit
balance *= 1.02
return round(balance, 2)
def wrong_order(months, deposit):
balance = 0
for _ in range(months):
balance *= 1.02
balance += deposit
return round(balance, 2)
# ---- tests ----
print(balance_after(12, 100))
print(wrong_order(12, 100))
Task 3: Process transactions in sequence
Write process(start, transactions). Each transaction is a tuple like ("deposit", 50) or ("withdraw", 80). Apply them in order. A withdrawal that would make the balance negative is rejected (balance unchanged). Return the final balance and a list of rejected transaction numbers (starting from 1). Show by example that processing the same list in a different order can change which are rejected.
Starter file (write your code where it says pass # your code here):
def process(start, transactions):
pass # your code here
# ---- tests ----
t = [("withdraw", 80), ("deposit", 50), ("withdraw", 30)]
print(process(40, t))
print(process(40, [t[1], t[0], t[2]]))
Expected output when your code is correct:
(60, [1]) (10, [3])
Hint
Model solution
def process(start, transactions):
balance = start
rejected = []
for number, (kind, amount) in enumerate(transactions, start=1):
if kind == "deposit":
balance += amount
elif kind == "withdraw":
if amount > balance:
rejected.append(number)
else:
balance -= amount
return balance, rejected
# ---- tests ----
t = [("withdraw", 80), ("deposit", 50), ("withdraw", 30)]
print(process(40, t))
print(process(40, [t[1], t[0], t[2]]))
Learning objectives
By the end of this page you should be able to:
- Explain how the order of instructions affects what a program does and what it outputs.
- Construct programs whose statements run in the correct sequence: inputs and initialisation before use, calculations before output, checks before actions.
- Identify why a loop is infinite and fix it so its condition eventually becomes false.
- Explain what deadlock is and describe ways to avoid it, such as a fixed lock order or timeouts.
- Use test data with expected results to detect incorrect output caused by sequencing errors.
Sequence
Sequence is the most basic control structure: statements run one after another, top to bottom, exactly in the order written. Changing the order can change the output, cause an error, or both, even when every line is individually correct.
Rules of thumb for a correct sequence
- Define before use: a variable must be assigned before it is read, or Python raises a NameError.
- Initialise before a loop:
total = 0goes before the loop that adds to it, not inside it. - Calculate before output: print a result only after every step that changes it.
- Check before acting: test that a book is available before lending it; validate input before using it.
- Save values you are about to overwrite: swapping needs a temporary variable.
- Order inside conditions matters too:
i < len(items) and items[i] != "quit"is safe becauseandstops at the first False (short-circuit evaluation).
Infinite loops
A loop is infinite when its condition can never become false. Common causes:
- The loop variable is never updated (missing
n = n - 1). - It is updated in the wrong direction, or the update is inside an if that never runs.
- An exact test such as
x != 10that the variable jumps over (1, 3, 5, ... 9, 11). - Waiting for something that never happens, such as a resource that never becomes ready.
Avoid them by checking that every loop has: an initialised variable, a condition that tests it, and an update that moves it towards making the condition false. Prefer < or > to !=, and add a maximum number of tries when waiting.
Deadlock
Deadlock happens when two or more processes each hold a resource and wait for a resource held by another, so none can continue: a circular wait. Example: ShelfWise's desk app locks catalogue.csv and waits for loans.csv, while the report app has locked loans.csv and waits for catalogue.csv.
- Lock ordering: every program acquires resources in the same order, so a cycle cannot form.
- Request everything at once: take all needed resources together or none.
- Timeouts: if a resource is not granted in time, release what you hold and retry later.
- Hold locks briefly: lock, do the minimum work, release.
Incorrect output
Wrong sequencing often produces no error at all, just a wrong answer (a logic error). Detect it by testing with data whose expected result you worked out by hand, including boundary cases, and by tracing (B2.1.4).
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Explain, with an example, how the order of instructions can affect the output of a program. [3]
2. The loop below should print 5, 4, 3, 2, 1. Identify why it never stops and construct a correction. [3]
n = 5
while n > 0:
print(n)
n = n - 1 inside the loop, after the print [1].3. State the output of each version. [2]
# Version A # Version B
total = 0 total = 0
for x in [2, 3, 4]: for x in [2, 3, 4]:
total = total + x total = total + x
print(total) print(total)
2, 5, 9 on separate lines [1]; B: 9 only, because the print is after the loop [1].4. Explain what is meant by deadlock, and describe two ways it can be avoided. [4]
5. These lines should swap the values of a and b, but print Emma Emma. Construct a correct sequence. [3]
a = "Dune" b = "Emma" a = b b = a print(a, b)
temp = a [1], then a = b, b = temp, giving Emma Dune [1]. (Accept a, b = b, a with explanation.)6. Describe how testing can reveal incorrect output caused by an error in the sequence of instructions. [3]