Skip to content

B.2 · Programming

IB Computer Science SL · Topic 6

6.1

Scope and prerequisites

This handout teaches Theme B2, Programming, for the course first assessed in 2027, using Python.

Prerequisites: computational thinking from B1 (decomposition, abstraction, algorithms as flowcharts and pseudocode). You should be able to run a short Python program and read its output.

6.2

Programming fundamentals

Why does a working program fail on Monday?

A shop's checkout program has run for a month. On Monday a customer types two instead of 2 for the quantity and the program crashes. Nothing in the code changed: the input did. Good programs are written for every input they might meet, not only the ones the programmer tried.

Variables and data types

A variable 变量 is a named store for a value that can change while the program runs. A constant 常量 is a named value that should not change; in Python it is written in capitals by convention, such as VAT_RATE = 0.2.

Data types: integer (7), real (3.5), char ('A'), string (“hello”), boolean (true/false)
The basic data types: integer, real, char, string and boolean

Every value has a data type 数据类型, which decides what it can store and what operations work on it.

Type Python Example Use
integer int 42 counts, indexes
real float 3.75 measurements, money in a calculation
Boolean bool True flags, conditions
string str "Ada" text
  • int("42") turns text into an integer and str(42) turns a number into text. This casting 类型转换 is needed because input() always returns a string.
  • 7 / 2 is 3.5; 7 // 2 is 3 (integer division 整除); 7 % 2 is 1 (the remainder, modulo 取模).

Strings

A string 字符串 is a sequence of characters, indexed from 0.

code = "ib-2027"
len(code)        # 7
code[0]          # "i"
code[3:7]        # "2027": from index 3 up to, not including, 7
code.upper()     # "IB-2027"
code.find("-")   # 2; -1 if not found
"2027" in code   # True

Python strings are immutable 不可变的: code.upper() returns a new string and leaves code unchanged. Joining strings with + is concatenation 连接.

Exceptions: handling bad input

An exception 异常 is an error raised while the program runs, such as ValueError for int("two") or ZeroDivisionError for 5 / 0. Unhandled, it stops the program. A try … except block catches it:

while True:
    text = input("Quantity: ")
    try:
        qty = int(text)
        break
    except ValueError:
        print("Enter a whole number.")

The loop repeats until the cast succeeds, so the program never crashes on two. A finally block, if present, runs whether or not an exception occurred: it is used to close files.

Debugging and trace tables

There are three kinds of error:

A trace table with columns count, total, output
A trace table records each variable's value as the program runs
Kind When it shows Example
syntax error before the program runs a missing colon after if x > 0
runtime error while it runs, as an exception an index past the end of a list
logic error never reported: the output is wrong < where <= was meant

A trace table 跟踪表 records the value of each variable after each step, by hand. It is the standard way to find a logic error and a common exam question.

total = 0
for k in range(1, 5):
    if k % 2 == 0:
        total = total + k
print(total)
k k % 2 == 0 total
0
1 False 0
2 True 2
3 False 2
4 True 6

Output: 6. Note that range(1, 5) stops before 5. Other debugging techniques are print statements at key points, breakpoints in a debugger 调试器 that pause the program and show the variables, and stepping through one line at a time.

Vocabulary Train
English
variable/ˈveərɪəbl/
constant/ˈkɒnstənt/
data type/ˈdeɪtə taɪp/
casting/ˈkæstɪŋ/
integer division/ˈɪntɪdʒə dɪˈvɪʒn/
modulo/məˈdjʊləʊ/
string/strɪŋ/
immutable/ɪˈmjuːtəbl/
concatenation/kənˌkætəˈneɪʃn/
exception/ekˈsepʃn/
trace table/treɪs ˈteɪbl/
debugger/ˈdiːbʌɡə/
6.3

Data structures

Static and dynamic structures

A static data structure 静态数据结构 has a size fixed when it is created, like an array in Java or C. A dynamic data structure 动态数据结构 grows and shrinks as the program runs, like a Python list.

Static Dynamic
size fixed changes at run time
memory reserved in advance, may be wasted used as needed
access direct by index, fast may need extra work to grow
risk overflow when full running out of memory

One- and two-dimensional arrays

A one-dimensional array 数组 stores items of one type under one name, each reached by its index 索引. In Python a list plays this role:

marks = [67, 82, 45, 90]
marks[2]          # 45
marks[2] = 50     # change one item
marks.append(71)  # add at the end: [67, 82, 50, 90, 71]
len(marks)        # 5

A two-dimensional array 二维数组 is a table: a list of rows, where each row is a list. The first index picks the row and the second the column.

A 3 by 4 grid of numbers with rows 0 to 2 and columns 0 to 3; the cell in row 1, column 2 is shaded and holds 5, so grid[1][2] == 5, row first then column
grid[row][col]: the row index comes first
grid = [[4, 7, 1, 9],
        [2, 8, 5, 3],
        [6, 0, 7, 4]]

row_total = 0
for col in range(len(grid[1])):
    row_total = row_total + grid[1][col]
print(row_total)   # 2 + 8 + 5 + 3 = 18

To visit every cell, nest two loops: the outer one over the rows, the inner one over the columns.

Stacks and queues

Both are abstract data types 抽象数据类型: defined by their operations, not by how they are stored.

A stack drawn as a container with A at the bottom, B and C above; push and pop both act at the top. A queue drawn as a row A, B, C; enqueue adds at the rear on the right and dequeue removes from the front on the left
Stack: one end does everything. Queue: add at the rear, remove from the front
Stack Queue
order LIFO 后进先出: last in, first out FIFO 先进先出: first in, first out
add push onto the top enqueue at the rear
remove pop from the top dequeue from the front
look peek at the top peek at the front
uses undo, back button, function calls print jobs, keyboard buffer, task scheduling
stack = []
stack.append("A"); stack.append("B"); stack.append("C")   # push
stack.pop()        # "C"

from collections import deque
queue = deque()
queue.append("A"); queue.append("B"); queue.append("C")   # enqueue
queue.popleft()    # "A"

Before a pop or dequeue, check isEmpty: removing from an empty structure is an underflow 下溢. Pushing onto a full fixed-size stack is an overflow 溢出.

Vocabulary Train
English
static data structure/ˈstætɪk ˈdeɪtə ˈstrʌktʃə/
dynamic data structure/daɪˈnæmɪk ˈdeɪtə ˈstrʌktʃə/
array/əˈreɪ/
index/ˈɪndeks/
two-dimensional array/tuː daɪˈmenʃənl əˈreɪ/
abstract data type/ˈæbstrækt ˈdeɪtə taɪp/
LIFO/ˈlaɪfəʊ/
FIFO/ˈfaɪfəʊ/
underflow/ˌʌndəˈfləʊ/
overflow/ˌəʊvəˈfləʊ/
6.4

Programming constructs

Sequence, selection and iteration

Every algorithm is built from three constructs: sequence 顺序 (steps in order), selection 选择 (if, elif, else) and iteration 迭代 (loops).

Loop Python Use when
count-controlled for i in range(n): the number of repeats is known
condition-controlled while condition: repeat until something happens
over a collection for item in items: visit each item once

A while loop whose condition never becomes false is an infinite loop 无限循环. Nested selection or loops place one construct inside another; indentation shows which is inside which.

Functions, parameters and scope

A function 函数 is a named block of code that can be called many times. It takes parameters 参数 and may return 返回 a value. Splitting a program into functions is modularity 模块化: each part is written, tested and reused on its own.

def mean(values):
    """Return the mean of a non-empty list of numbers."""
    total = 0
    for v in values:
        total = total + v
    return total / len(values)

print(mean([4, 8, 9]))   # 7.0
  • A local variable 局部变量 such as total exists only inside the function while it runs.
  • A global variable 全局变量 is defined at module level and can be read where Python scope and name-binding rules resolve to it; a local name can shadow it. Using many globals makes a program hard to test, because any function might change them.
  • The docstring states the function's contract: what it needs (a non-empty list) and what it returns. mean([]) breaks the contract and raises ZeroDivisionError.
A program contract in three boxes: inputs with stated conditions and boundary cases, a finite unambiguous procedure, expected outputs for every tested category
A function's contract: the inputs it accepts, including boundary cases, and the output it promises for each

Test a function against its contract: normal values, boundary cases 边界情形 at the edge of what it accepts (a one-item list), and invalid values it should reject (an empty list).

Vocabulary Train
English
sequence/ˈsiːkwəns/
selection/sɪˈlekʃn/
iteration/ˌɪtəˈreɪʃn/
infinite loop/ˈɪnfɪnət luːp/
function/ˈfʌŋkʃn/
parameter/pəˈræmɪtə/
return/rɪˈtɜːn/
modularity/ˌmɒdjʊˈlærɪti/
local variable/ˈləʊkl ˈveərɪəbl/
global variable/ˈɡləʊbl ˈveərɪəbl/
boundary case/ˈbaʊndəri keɪs/
6.5

Algorithms

Measuring efficiency: Big O

Big O notation 大O表示法 gives an asymptotic upper bound for how a chosen cost grows with input size $n$. State whether the cost being analysed is worst-case, average-case or best-case. Constants and smaller terms are dropped.

Big O Name Example Steps for $n = 1000$
$O(1)$ constant reading marks[2] 1
$O(\log n)$ logarithmic binary search about 10
$O(n)$ linear linear search 1000
$O(n^2)$ quadratic bubble sort, selection sort about 1 000 000

A single loop over the data is usually $O(n)$; a loop inside a loop over the same data is usually $O(n^2)$.

Steps against input size n from 1 to 10 for O(1), O(log n), O(n) and O(n squared); the constant and logarithmic lines stay almost flat, the linear line rises steadily, and the quadratic curve shoots past 50 steps
Growth, not speed on one input: O(1) < O(log n) < O(n) < O(n²)

Linear and binary search

A linear search 线性查找 checks each item in turn. It works on any list, sorted or not, and is $O(n)$.

def linear_search(items, target):
    for i in range(len(items)):
        if items[i] == target:
            return i
    return -1

A binary search 二分查找 needs a sorted list. It checks the middle item and throws away the half that cannot hold the target, so each probe halves what is left: $O(\log n)$.

def binary_search(items, target):
    low, high = 0, len(items) - 1
    while low <= high:
        mid = (low + high) // 2
        if items[mid] == target:
            return mid
        elif items[mid] < target:
            low = mid + 1
        else:
            high = mid - 1
    return -1
Binary search for 23 in the sorted list 2, 5, 8, 12, 16, 23, 38, 56, 72 with indexes 0 to 8. Probe 1 at index 4 finds 16, less than 23, so go right; probe 2 at index 6 finds 38, greater than 23, so go left; probe 3 finds 23 at index 5. Discarded items are greyed
Each probe discards half of what remains

Trace for 23: low 0, high 8, mid 4 (16 < 23) → low 5; mid $(5 + 8) // 2 = 6$ (38 > 23) → high 5; mid 5: found, return 5. On an unsorted list binary search can miss a value that is there, so the contract must require sorted input.

Bubble sort and selection sort

A bubble sort 冒泡排序 compares each pair of neighbours and swaps them if they are in the wrong order. After each pass the largest remaining item has "bubbled" to the end.

A list where the first pair 5 and 2 is out of order, shown swapping to 2 and 5, with a note to repeat for each pair
One comparison in another example: bubble sort swaps neighbours that are out of order, then continues through the pass
def bubble_sort(a):
    n = len(a)
    for p in range(n - 1):
        swapped = False
        for i in range(n - 1 - p):
            if a[i] > a[i + 1]:
                a[i], a[i + 1] = a[i + 1], a[i]
                swapped = True
        if not swapped:
            break

The swapped flag stops early when a pass makes no swaps: the list is already sorted.

A selection sort 选择排序 finds the smallest item in the unsorted part and swaps it into the next place.

def selection_sort(a):
    for i in range(len(a) - 1):
        smallest = i
        for j in range(i + 1, len(a)):
            if a[j] < a[smallest]:
                smallest = j
        a[i], a[smallest] = a[smallest], a[i]

Passes of each sort on [5, 1, 4, 2]:

After pass Bubble sort Selection sort
1 [1, 4, 2, 5] [1, 5, 4, 2]
2 [1, 2, 4, 5] [1, 2, 4, 5]
3 no swaps: stop [1, 2, 4, 5]

Both are $O(n^2)$. Selection sort makes at most $n - 1$ swaps; bubble sort can stop early on a nearly sorted list.

Explore

Search probes and boundary cases

Compare linear search with binary search on sorted data. Trace a match or an absent target; indices start at zero.

Vocabulary Train
English
linear search/ˈlɪnɪə sɜːtʃ/
binary search/ˈbaɪnəri sɜːtʃ/
bubble sort/ˈbʌbl sɔːt/
selection sort/sɪˈlekʃn sɔːt/
Big O notation/bɪɡ əʊ nəʊˈteɪʃn/
6.6

File processing

Reading and writing text files

A program's variables are lost when it ends; a file 文件 keeps data between runs. Open the file with a mode 模式, use it, then close it.

Mode Meaning If the file exists
"r" read read from the start
"w" write emptied first
"a" append add to the end
The same two-line file scores.txt, holding Ada,91 and Ben,78, after each mode: read leaves it unchanged; write empties it first, so it holds only Cy,85; append adds Cy,85 after the two lines
Mode "w" destroys what was there; mode "a" keeps it
with open("scores.txt", "a") as f:
    f.write("Ada,91\n")

best_name, best = "", -1
with open("scores.txt", "r") as f:
    for line in f:
        name, score = line.strip().split(",")
        if int(score) > best:
            best_name, best = name, int(score)
print(best_name, best)
  • with closes the file automatically, even if an exception occurs.
  • Each line read ends in "\n"; strip() removes it before split(",") breaks the line into fields.
  • Opening a missing file for reading raises FileNotFoundError: catch it with try … except.
Vocabulary Train
English
file/faɪl/
mode/məʊd/
6.7

Practice

  1. State the data type best suited to each: (a) the number of students in a class; (b) whether a door is locked; (c) a postcode such as "SW1A 1AA"; (d) a temperature of 21.5 °C.
  2. s = "Programming". Give (a) len(s); (b) s[3:7]; (c) s.find("g").
  3. Classify each error as syntax, runtime or logic: (a) print("Hi"; (b) a loop that adds one item too few; (c) int("abc").
  4. Complete a trace table for x = 1 then while x < 20: x = x * 3, and state the final value of x.
  5. The items 10, 20 and 30 are pushed onto an empty stack, then one item is popped and 40 is pushed. State the item on top.
  6. The same items are put through a queue: enqueue 10, 20, 30, dequeue once, enqueue 40. State the item at the front.
  7. For the list [3, 8, 12, 19, 25, 31, 40], list the values that a binary search for 31 compares with.
  8. Show the list [6, 3, 8, 2] after each pass of a bubble sort.
  9. Write a Python function count_over(marks, limit) that returns how many marks in the list are greater than limit.
  10. Explain why opening "log.txt" with mode "w" each time a program starts loses data, and state the fix.

Answers.

  1. (a) integer; (b) Boolean; (c) string, as it holds letters and spaces; (d) real.

  2. (a) 11; (b) "gram"; (c) 3.

  3. (a) syntax: a missing bracket; (b) logic; (c) runtime: a ValueError.

  4. x takes the values 1, 3, 9, 27; the loop stops when x is 27. Final value 27.

  5. Push 10, 20, 30; pop removes 30; push 40. Top: 40.

  6. Enqueue 10, 20, 30; dequeue removes 10; enqueue 40. Front: 20.

  7. low 0, high 6: mid 3, value 19 < 31, so low = 4; mid $(4 + 6) // 2 = 5$, value 31: found. Compared with 19 and 31.

  8. Pass 1: [3, 6, 2, 8]; pass 2: [3, 2, 6, 8]; pass 3: [2, 3, 6, 8].

  9. One answer:

    def count_over(marks, limit):
        count = 0
        for m in marks:
            if m > limit:
                count = count + 1
        return count
    
  10. Mode "w" empties an existing file before writing, so the earlier log is lost. Open it with "a" to append.

  11. power(2, 5) calls itself with e = 4, 3, 2, 1, 0: 6 calls, returning $2^5 =$ 32.

  12. It calls itself for ever; each call adds a frame to the call stack until memory runs out, a stack overflow (in Python a RecursionError).

6.8

Exam tips

  • In a trace table, give a new row each time a variable changes, and show the output separately. Check where range stops.
  • State the indexing convention (Python indexes from 0) before tracing an array or a search.
  • For a binary search answer, say that the list must be sorted and give low, high and mid at every probe.
  • Bubble sort and selection sort are both $O(n^2)$: compare them by swaps, early stopping and passes, not by Big O.
  • "Explain" a stack or queue with its order (LIFO or FIFO), its two operations and a real use.
  • When writing code, use clear names, close files with with, and handle bad input with try … except.

More topics in IB Computer Science SL

Log in or create account

IGCSE, A-Level & AP