Home › Theme B › B2 › B2.3 › B2.3.1

B2.3.1 Getting the order of instructions right

SL + HLCommand term: Construct

1. 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.

Version A
Version B

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.

Puzzle:
    Press Run.

    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.

    Loop:
    Passes: 0  
    Fix:

    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.

    Strategy:

    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.

    Round 0/10Score 0Streak 0Best 0
    Press start!

    7. 45-second speed round: does it stop?

    A new loop each time. Will it terminate, or run forever?

    Time 45sScore 0Streak 0Best 0
    Press start!
    ShelfWise · Sprint 3, task 1. Sprint 3 builds the menu-driven console app. First, a teammate's checkout code has its statements in the wrong order, and two loops never stop. Fix the sequence without adding new logic to checkout, and make both loops terminate.

    Expected output

    Ana borrowed Dune - copies left: 1 True False False [['Ana', 'Dune']] Reminder: 3 day(s) left Reminder: 2 day(s) left Reminder: 1 day(s) left Doing search Doing lend Goodbye Doing search Goodbye

    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

      Next task (B2.3.2): the menu itself, with if / elif / else choosing what each command does.

      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.

      Set up in PyCharm
      1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
      2. Right-click the project → New → Python File, using the file name shown on the task.
      3. Press Copy starter and paste it in, or press Download .py.
      4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
      How the tasks work
      1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
      2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
      3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
      4. Written parts: answer in your notebook first, then check the model answer.
      Average

      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):

      File: b2_3_1_average.py
      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
      Sequence matters: you must count an attempt before deciding if the user is locked out.
      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.

      File: b2_3_1_average_solution.py
      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"])
      
      Moderate

      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):

      File: b2_3_1_moderate.py
      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
      Swap two lines only.
      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.

      File: b2_3_1_moderate_solution.py
      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))
      
      Challenging

      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):

      File: b2_3_1_challenging.py
      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
      Use enumerate(..., start=1) to number transactions.
      Model solution
      File: b2_3_1_challenging_solution.py
      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:

      1. Explain how the order of instructions affects what a program does and what it outputs.
      2. Construct programs whose statements run in the correct sequence: inputs and initialisation before use, calculations before output, checks before actions.
      3. Identify why a loop is infinite and fix it so its condition eventually becomes false.
      4. Explain what deadlock is and describe ways to avoid it, such as a fixed lock order or timeouts.
      5. 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 = 0 goes 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 because and stops 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 != 10 that 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]

      Statements execute in the order written / sequentially [1]; if an output or calculation is placed before the step that updates a value, it uses the old value [1]; e.g. printing a fine before the teacher discount is applied shows the undiscounted fine / using a variable before it is assigned causes an error [1].

      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 is never changed inside the loop [1], so n > 0 is always true / the condition never becomes false [1]. Add 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)
      A: 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]

      Two or more processes are each holding a resource while waiting for a resource held by another [1], so none can proceed / circular wait [1]. Avoidance, [1] each up to [2]: all processes request resources in the same fixed order; a process requests all its resources at once; timeouts so a waiting process releases what it holds and retries; minimise how long locks are held.

      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)
      The first assignment overwrites the original value of a, which is then lost [1]. Store it first: 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]

      Choose test data and work out the expected output by hand beforehand [1]; run the program with that data and compare actual with expected output [1]; a mismatch reveals the logic error, which can then be located by tracing / breakpoints / debug prints; include boundary cases [1].