YOUR B2 REVISION ROUTE
B2 connects programming fundamentals, data structures, sequence/selection/iteration, functions, algorithms and file processing. This page covers B2.1.1 through B2.5.1, with B2.4.4 and B2.4.5 marked HL only.
Use Revise to reconstruct the worked examples before checking their outcomes. In Flashcards, filter by subsection or individual objective, reveal answers and select ideas to revisit. The 324 cards include 288 common SL/HL cards and 36 HL-only recursion cards.
Changing a filter keeps your selections. The full revision list includes selected cards hidden by filters, and can be copied. Selections last while this page is open.
B2.1.1 | VARIABLES, TYPES AND SCOPE
A variable name refers to a value or object according to the language’s rules. Use types suited to the data: integers for whole counts, floating-point values for real-number approximations, Booleans for logical state and strings for text. Python str also represents one-character text; Java has a separate char type.
A local name belongs to a function’s scope. A module-level Python name is global to that module; it is not automatically a local variable in every function. Assignment inside a function normally establishes a local binding unless declared otherwise.
Passing explicit parameters and returning results reduces hidden dependencies. A local parameter can still refer to a mutable list shared with the caller, so local scope does not imply that every object has been copied.
WORKED | LOCAL REBINDING AND SHARED MUTATION
def adjust(score, values):
score = score + 2
values.append(score)
return score
score = 10
values = [8]
result = adjust(score, values)
print(score, result, values)
Output: 10 12 [8, 12]. The local score is rebound to 12 without rebinding the caller’s score. append changes the shared list object, so the caller sees that mutation. result receives the returned 12.
For Java, parameter values are copied. When the value is an object reference, both caller and parameter can refer to the same object; rebinding the parameter does not rebind the caller’s variable.
B2.1.2 | EXTRACT AND MANIPULATE SUBSTRINGS
A substring is a contiguous part of a string. Python indexing begins at 0, and text[start:stop] includes start but excludes stop. A negative index counts from the end; a slice can include a step. Python strings are immutable, so transformations return strings rather than changing individual characters in place.
text = "COMPUTER"
print(text[0])
print(text[1:4])
print(text[-1])
print(text.lower())
Outputs: C, OMP, R, computer. The substring has positions 1, 2 and 3, not position 4. A single invalid index raises IndexError, while ordinary slices can clip to the available bounds.
Java substring(begin, end) also excludes end, but Java string positions are UTF-16 code-unit indexes. Python str indexes Unicode code points; neither convention always corresponds to one visible grapheme. State assumptions when tracing non-ASCII text.
B2.1.3 | EXCEPTION HANDLING
An exception interrupts normal control flow when an operation cannot complete normally. Catch a relevant error around the operation that may raise it; do not use one broad catch to hide unrelated defects.
Python try runs the guarded code; except handles a matching exception; else runs if the try suite completes without an exception; finally performs cleanup on exit from that construct. An unmatched exception can propagate after finally. with is a convenient way to manage file cleanup.
raw = "0"
try:
number = int(raw)
result = 12 / number
except ValueError:
print("Not an integer")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(result)
finally:
print("Check finished")
Output: Cannot divide by zero, then Check finished. A successful conversion does not establish that division is valid. Java uses try/catch/finally with its own exception types.
B2.1.4 | DEBUGGING TECHNIQUES
Distinguish syntax errors, runtime failures and logic errors. A logic error can produce an incorrect result without an exception. Reproduce the fault with small known input and an independently calculated expected result.
Use breakpoints to pause, step into a helper when investigating it, step over a call when its internals are not relevant, and inspect variables or watches. A debugger usually pauses before the highlighted line executes; the displayed values can therefore be the old values.
For a running total, trace the accumulator before and after each update. A print trace can expose a fault, but avoid changing state while merely trying to observe it. Fix the cause and rerun the failing case plus relevant boundary cases.
B2.2.1 | STATIC AND DYNAMIC STRUCTURES
A fixed-size structure has a capacity that is not automatically changed during its normal use. A dynamic structure can change logical size. Distinguish size, the number of stored items, from capacity, the available storage slots.
A Java array has fixed length. Java ArrayList and Python list provide resizable sequence behaviour, but resizing can involve allocating and copying. A linked representation has different access and allocation costs. “Dynamic” does not mean every operation is constant time or that memory is unlimited.
A toy doubling-capacity model can illustrate amortized append behaviour: occasional copies cost more, while many appends fit existing capacity. Do not mistake the toy capacity sequence for a guarantee of a particular runtime’s implementation.
B2.2.2 | ARRAYS, LISTS AND TWO-DIMENSIONAL DATA
An index selects a position, not the value stored there. In zero-based sequences, valid non-negative indexes run from 0 through length − 1. Updating an existing position and inserting a new item have different effects on size and later positions.
A two-dimensional collection can be traversed row by row. For Python nested lists, avoid [[0] * columns] * rows when independent rows are required, because that repeats references to the same row. Build each row separately.
grid = [[4, 7, 2], [5, 1, 6]]
total = 0
for row in grid:
row_total = 0
for value in row:
row_total = row_total + value
total = total + value
print(row_total)
print(total)
Outputs: 13, 12, 25. Reset the row total for each row, but keep the grand total outside both loops. Python list append adds one item; Java ArrayList uses add, get and set. Java remove(index) differs from removing an Integer object by value.
B2.2.3 | STACK: LAST IN, FIRST OUT
A stack adds and removes at the top. push adds, pop removes and returns the top item, and peek inspects it without removal. Popping an empty stack is underflow. A bounded implementation must also define how it rejects a push when full.
Starting empty, push A, push B, pop returns B, then peek gives A. In an array implementation with top as the last occupied index, empty can be top = −1 and size = top + 1. A different top convention needs different updates.
Python list append/pop can implement top-at-end stack behaviour; Java ArrayDeque provides suitable stack operations. Undo histories and active function calls are applications, but distinguish a user-visible undo stack from the runtime’s call stack.
B2.2.4 | QUEUE: FIRST IN, FIRST OUT
A queue enqueues at the rear and dequeues from the front. front/peek inspects the next item to leave. Starting empty, enqueue A, B, C, then dequeue returns A, leaving B before C.
For a circular array queue, this convention uses front as next read position, rear as next write position, and count to distinguish empty from full. Advance an index with (index + 1) % capacity. Equal front/rear can mean either full or empty, depending on count.
| Capacity 5 sequence | Physical slots 0..4 | Logical order | front / rear / count |
|---|---|---|---|
| Enqueue A–D; dequeue A and B; enqueue E,F,G | [F, G, C, D, E] | C, D, E, F, G | 2 / 2 / 5 |
Python collections.deque supports efficient append and popleft. list.pop(0) shifts later elements, so it has a different cost. FIFO service order does not imply tasks finish in the same order when processing runs concurrently.
B2.3.1 | SEQUENCE AND DEPENDENCIES
Sequence specifies the order in which instructions run. Obtain inputs before converting them; calculate intermediate results before using them; update state before reporting the intended final result. A valid set of instructions in the wrong order can still violate the objective.
For a price calculation: convert quantity, calculate subtotal, calculate discount, then calculate final total. Printing before calculating can show an old value or access a name not yet bound.
Resource-ordering problems also depend on sequence. If one task holds a printer while waiting for a scanner and another holds the scanner while waiting for the printer, neither can progress. Consistent coordinated acquisition order can prevent that circular wait; a sequential toy example is not a complete concurrency system.
B2.3.2 | SELECTION AND BOOLEAN CONDITIONS
A Python if/elif/else chain selects the first matching branch and skips later alternatives. Independent if statements can all run. With overlapping grade thresholds, put the more restrictive high threshold first or use justified non-overlapping ranges.
AND requires both conditions; OR permits either; NOT reverses truth. For inclusive age 12–17, use age >= 12 and age <= 17. Invalid outside that range uses age < 12 or age > 17. Group alternatives before a blocking rule.
age = 10
member = True
suspended = False
eligible = (12 <= age <= 17 or member) and not suspended
print(eligible)
Output: True under this fictional rule, which allows registered members outside the age range but blocks all suspended people. Java uses &&, || and !. Python == compares string values; Java String content is normally compared with equals rather than reference ==.
B2.3.3 | LOOPS, BODIES AND PROGRESS
The loop body is the repeated block, possibly containing several instructions, selections or another loop. Python indentation identifies it. for visits a supplied sequence; while checks its continuation condition before every iteration and can execute zero times.
range(1, 4) supplies 1, 2, 3. range(3, 0, −1) counts down 3, 2, 1. The stop is excluded. A while loop needs state changes that allow progress; continue can accidentally skip a required update. break exits the nearest enclosing loop.
total = 0
number = 1
while number <= 3:
total = total + number
number = number + 1
print(total)
Output: 6. Body executions use number 1, 2, 3; the final test sees 4 and is false. total = total + number reads the old accumulated total and replaces it with the sum. Initialization inside every iteration would discard previous work.
WORKED | NESTED LOOPS AND STOP CONDITIONS
| Construct | Trace / meaning |
|---|---|
| Outer values 1,2; inner values 1,2,3 | Pairs (1,1), (1,2), (1,3), (2,1), (2,2), (2,3) |
| Sentinel input 4,7,0; add only nonzero values | Total 11; sentinel is consumed but excluded |
| Java do/while | Body runs before testing; true continues |
| Pseudocode REPEAT UNTIL | Body runs before testing; true stops |
The inner loop completes and restarts for every outer iteration. In the rectangular example it runs 2 × 3 body executions, not 2 + 3. Check whether inner bounds depend on the outer variable before multiplying simple fixed counts.
An empty list, zero repetitions where permitted, a first-input sentinel and exact boundaries are high-value tests. Do not infer final output from the final stored loop counter.
B2.3.4 | FUNCTIONS AND MODULARIZATION
A parameter names an input in a definition; an argument supplies its value in a call. A return provides a usable result and ends that call. print displays text but does not substitute for returning the enclosing function’s calculated result.
A focused function contract specifies inputs, result, error policy and side effects. Decompose a report into calculation, classification and formatting, connected by a coordinating function. High cohesion means related work supports one purpose; coupling concerns dependencies between units.
def double(number):
return number * 2
result = double(6)
print(result)
Output: 12. A Python function with no explicit returned value supplies None. Java methods declare a returned type or void. Keep explicit parameters and returned values rather than relying on changing globals when that makes the interface clearer.
WORKED | MODULES, IMPORTS AND TESTING
A Python module can be a .py file grouping related definitions. import report_tools allows report_tools.percentage(...). The first ordinary import executes top-level statements, so prompts and prints outside a guard can run during import.
Use if __name__ == "__main__": main() to control application startup. The guard only controls its own block; it does not suppress all top-level execution. Keep related reusable calculations in a module and startup in a coordinating entry script.
Unit tests check individual units; integration tests check their cooperation. Refactoring changes structure while preserving required observable behaviour, so retain tests for calculations, output order, error policies and intentional mutations.
B2.4.1 | CALCULATE BIG O AND SCALABILITY
Define n, the measured resource and the case. Big O is an asymptotic upper bound, not a number of seconds and not automatically a synonym for worst case. In standard classroom classification, report an informative bound for the specified cost.
Count actual repeated work: sequential stages add, while nested counts depend on their bounds. Drop fixed multipliers and lower-order terms when naming the dominant standard growth. An O(n) helper called n times can make O(n²) work.
Constants and implementation still matter for observed timings. A smaller growth class does not promise faster execution at every small size.
WORKED | FROM COUNTS TO GROWTH
| Pattern / count | Standard bound | Reason |
|---|---|---|
| One indexed access, fixed-size model | O(1) | No growth in repeated work |
| Two consecutive full scans: 2n | O(n) | Add then drop fixed factor |
| n outer iterations; inner fixed at 3 | O(n) | 3n body executions |
| All ordered pairs: n² | O(n²) | n × n |
| Unique pairs: n(n−1)/2 | O(n²) | Quadratic dominant term |
| Repeated halving with constant work | O(log n) | Logarithmically many reductions |
| Linear work at each log n level | O(n log n) | Multiply level work by levels |
For independent input sizes n and m, all pairings cost O(nm), not automatically O(n²). Doubling n makes a quadratic model about four times larger; it adds one level to log₂ n. Specify any timing-estimate assumptions separately.
B2.4.2 | CONSTRUCT AND TRACE SEARCHES
Linear search checks candidates in sequence and needs no sorted order. Return the matching index immediately, but put the not-found return after the loop. The shown version finds the first match from the left.
Binary search requires ascending comparable data for this version. Keep inclusive indexes low and high, calculate middle, and compare the stored middle value. On a too-small value use low = middle + 1; on a too-large value use high = middle − 1. Stop when low > high.
A low == high interval still has one candidate, so use low <= high. Basic binary search returns a reached matching occurrence, not necessarily the first duplicate. Check a -1 result before Python indexing, where [-1] otherwise selects the final item.
WORKED | BINARY SEARCH WITH AN ABSENT TARGET
| Search 20 in [3,7,11,15,19,23,27,31] | low before | high before | middle / value | Next action |
|---|---|---|---|---|
| Probe 1 | 0 | 7 | 3 / 15 | low = 4 |
| Probe 2 | 4 | 7 | 5 / 23 | high = 4 |
| Probe 3 | 4 | 4 | 4 / 19 | low = 5 |
| Exit | 5 | 4 | No access | False test; return -1 |
The worst-case search time is O(n) for linear search and O(log n) for indexed binary search; both shown iterative forms use O(1) auxiliary space. Include sorting if required as part of the task. A midpoint probe can perform more than one primitive comparison.
B2.4.3 | BUBBLE SORT AND SELECTION SORT
Bubble sort compares adjacent items and swaps when the left key is greater. A left-to-right pass settles the largest active value at the right; shrink the active prefix. Reset swapped before each pass, set it when a swap occurs and stop after a no-swap pass.
Selection sort remembers the minimum index in the remaining suffix, then swaps that item into the next prefix position after finishing the scan. Candidate updates are not swaps. A pass with no selection swap does not prove the remaining suffix is sorted.
The shown functions mutate the original collection. If no result is explicitly returned in Python, their return value is None; assigning that return back to the list variable would lose the binding to the sorted list.
WORKED | COUNT COMPARISONS AND EXCHANGES
| Initial [5,1,4,2,3] | Optimized bubble | Selection |
|---|---|---|
| Pass 1 result | [1,4,2,3,5] | [1,5,4,2,3] |
| Pass 2 result | [1,2,3,4,5] | [1,2,4,5,3] |
| Final comparison total | 9; a further no-swap pass checks | 10; all suffix scans |
| Actual swaps | 6 | 4 |
| Best-case time | O(n) with early stop | O(n²) |
| Worst-case time | O(n²) | O(n²) |
| Auxiliary space, compact in-place versions | O(1) | O(1) |
Selection makes n(n−1)/2 comparisons and at most n−1 actual non-self swaps. The strict-greater bubble version is stable; standard swap-based selection is not. Nearly sorted does not universally guarantee linear bubble time. A copying wrapper or saved visualization history changes memory usage.
B2.4.4 | RECURSION: MECHANISM AND APPLICATIONS HL ONLY
A recursive function solves a similar smaller problem, reaches a directly solvable base case, then returns through waiting callers. Each active call has separate local state in a stack frame. A base case must be correct and reachable for permitted inputs.
Trees contain subtrees, fractals repeat smaller shapes and quicksort recursively sorts pivot-based partitions. A complete constant-work-per-node tree traversal is O(n) time with O(h) stack space for height h. Balanced and chain-like trees have different depths.
Balanced or suitably averaged quicksort can be O(n log n) time, but repeated highly unbalanced partitions give O(n²). Ordinary in-place recursive implementations can have O(log n) balanced stack depth or O(n) worst-case depth. Allocating partition lists adds other storage costs.
A binary branching image can have exponentially many segments in depth while retaining only a linear-depth call chain. Total calls and simultaneously active calls are different measures.
B2.4.5 | CONSTRUCT AND TRACE NON-BRANCHING RECURSION HL ONLY
def sum_to(n):
if n == 0:
return 0
return n + sum_to(n - 1)
print(sum_to(3))
For non-negative integer n, the output is 6. Calls descend through arguments 3,2,1,0; results return 0,1,3,6. The pending operation is n plus the returned smaller sum, not n plus the smaller argument.
Non-branching means at most one recursive call per invocation; selection is allowed. Printing before a smaller call produces descent order, while printing after it produces unwinding order. A bare Python return supplies None.
Construct a contract, base result, justified reduction and use of the returned result. Factorial needs base 1; an empty sum needs base 0. A list index can increase while the remaining suffix decreases. Under unit-cost arithmetic, a length-n chain typically uses O(n) time and O(n) retained-frame space.
WORKED | PRINT BEFORE OR AFTER THE CALL HL ONLY
| For n = 3, base n = 0 prints nothing | Argument sequence | Printed sequence |
|---|---|---|
| print(n); recurse(n−1) | 3,2,1,0 | 3,2,1 |
| recurse(n−1); print(n) | 3,2,1,0 | 1,2,3 |
Trace the exact call site: after a smaller call returns, resume at the next instruction in its caller, not at the beginning of the caller’s body. Mark unassigned local values honestly. A valid large input may still exceed runtime stack resources.
B2.5.1 | OPEN, READ, WRITE, APPEND AND CLOSE
| Mode | Existing contents | Missing file |
|---|---|---|
| r | Preserved; read from current position | Opening fails |
| w | Truncated on successful open | Can create if location permits |
| a | New writes added at end | Can create if location permits |
A relative path resolves from the current working directory, not invariably the script folder. Use an appropriate explicit encoding, such as UTF-8 for the examples. with ensures Python file cleanup; Java try-with-resources closes declared resources.
read returns remaining text; readline returns one line, usually including its newline. Python EOF returns "", while a blank newline-only line is "\n". Check raw EOF before stripping. Convert text numbers before arithmetic.
write stores exactly the string supplied and adds no automatic newline. Append also does not insert a missing boundary before the new text. Maintain a documented record format.
WORKED | STREAM VALID SCORES INTO A TOTAL
total = 0
count = 0
with open("scores.txt", "r", encoding="utf-8") as source:
for line in source:
try:
score = int(line.strip())
except ValueError:
continue
total = total + score
count = count + 1
print(count, total)
For text lines 8, blank, bad, 5, this policy skips the two invalid lines and outputs 2 13. It still reads later valid data. A missing file is not handled by the inner conversion catch; use a separate relevant I/O policy.
For Java BufferedReader.readLine(), the terminator is omitted and EOF returns null; a blank line is an empty string. Scanner hasNextLine/nextLine provides another line-based approach. FileWriter can replace or append. State the API convention used in your trace.
B2 IN ONE INTEGRATED SCENARIO
A study tracker reads scores, validates each record, calculates a summary and saves a report. Use explicit text parsing and error policies; retain scores in a list only if later tasks need them. Decompose calculation and formatting into functions.
If you need one pass for total/count, a streaming loop is enough. If users repeatedly search by a sorted key, binary search may be appropriate, but include the cost of constructing and maintaining that order. A stable record sort may matter when equal scores should preserve a previous order.
Choose a stack for undo history and a queue for FIFO processing when those behaviours match the requirement. Do not choose a data structure just because it appeared in a recent lesson.
COMMON MISTAKES ACROSS B2
| Mistake | Correct reasoning |
|---|---|
| total = total + value is an equation | Evaluate using the old total, then assign the new value |
| print is a returned calculation | Display and returned results are separate |
| Two sequential loops must be quadratic | Add their actual costs |
| A no-swap selection pass means sorted | The remaining suffix can still be unordered |
| Found index -1 can be used in Python | Check failure before indexing |
| Local scope means a copied list | A local name may reference a shared mutable object |
| A blank file line is EOF | Use the API’s raw EOF convention |
| w adds another record | w replaces; a appends |
| Passing one test proves correctness | Cover boundaries, empty inputs and alternative paths |
COMMAND WORDS AND PRACTICE ROUTINE
| Command | How to answer |
|---|---|
| Construct | Supply a complete working algorithm or program matching the contract. |
| Trace | Follow the supplied version and record requested values, actions and outputs. |
| Describe | Give the relevant features and behaviour in sufficient detail. |
| Explain | Connect the mechanism to why or how it produces the effect. |
| Compare | Include relevant similarities and differences. |
| Evaluate | Weigh benefits and limitations against the stated requirements. |
First predict, then trace, then run. Write an expected result before using a debugger or executable example. For explanations, connect cause and consequence with because, therefore or resulting in when that link is justified.
Use the selected flashcards as a plan, revisit linked lessons for uncertain details and use the separate end-of-topic review for assessment practice. The workbook remains a separate forthcoming resource.