This handout teaches Theme B2, Programming, for the course first assessed in 2027, using Python. Sections marked AHL are for Higher Level only.
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.
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 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.
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.
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 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).
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)$.
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)$.
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.
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.
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
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.
A recursive function 递归函数 calls itself on a smaller version of the same problem. It needs two parts:
A base case 基线条件 that is answered directly, with no further call.
A recursive case 递归情形 that calls the function on a smaller input, moving towards the base case.
def total(items):
if items == []: # base case
return 0
return items[0] + total(items[1:]) # recursive case
Calls go down to the base case; results come back up
Each call is placed on the call stack 调用栈 with its own local variables. The calls wait until the base case returns, then finish in reverse order: last called, first finished, like a stack.
Tracing a recursive call
def power(b, e):
if e == 0:
return 1
return b * power(b, e - 1)
trees, nested folders, divide and conquer such as quicksort 快速排序
simple counting and running totals
Quicksort is recursive: pick a pivot, split the list into items less than and greater than the pivot, then quicksort each part. Its average case is $O(n \log n)$, much faster than the $O(n^2)$ sorts above for large $n$.
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.
s = "Programming". Give (a) len(s); (b) s[3:7]; (c) s.find("g").
Classify each error as syntax, runtime or logic: (a) print("Hi"; (b) a loop that adds one item too few; (c) int("abc").
Complete a trace table for x = 1 then while x < 20: x = x * 3, and state the final value of x.
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.
The same items are put through a queue: enqueue 10, 20, 30, dequeue once, enqueue 40. State the item at the front.
For the list [3, 8, 12, 19, 25, 31, 40], list the values that a binary search for 31 compares with.
Show the list [6, 3, 8, 2] after each pass of a bubble sort.
Write a Python function count_over(marks, limit) that returns how many marks in the list are greater than limit.
Explain why opening "log.txt" with mode "w" each time a program starts loses data, and state the fix.
AHL For power above, state the number of calls made by power(2, 5) and the value returned.
AHL Explain what happens when a recursive function has no base case.
Answers.
(a) integer; (b) Boolean; (c) string, as it holds letters and spaces; (d) real.
(a) 11; (b) "gram"; (c) 3.
(a) syntax: a missing bracket; (b) logic; (c) runtime: a ValueError.
x takes the values 1, 3, 9, 27; the loop stops when x is 27. Final value 27.