All subjects · Computer Science · WCP04 Advanced Practical Programming and Problem-solving
Subprograms, modules, libraries and text files
Edexcel IAL Computer Science · WCP04 Advanced Practical Programming and Problem-solving
Real programs are built from reusable pieces: your own functions, Python's standard library and data stored in files. The Unit 4 paper supplies code and data files, so you must be able to read and write them confidently.
Subprograms
- A function returns a value with return; a procedure carries out an action and returns nothing (Python returns None).
- Parameters are the names in the definition; arguments are the values passed in. A default value, as in def greet(name, greeting='Hello'), makes an argument optional.
- Variables created inside a subprogram are local: they exist only while it runs. Pass data in through parameters and out through return values instead of using global.
Modules and libraries
import math loads a module; use its contents as math.sqrt(). from random import randint loads one name. The PLS lists these library functions:
- math: ceil, floor, trunc, fabs, sqrt, pow, pi.
- random: randint(a, b) (both ends included), random() (a float from 0 up to but not including 1), uniform(a, b) (a float between a and b; the PLS says a <= X < b, and Python's documentation adds that b itself may occasionally appear because of float rounding), shuffle(list).
- copy: copy (shallow) and deepcopy (copies nested lists too).
- time: time() (seconds since the Unix epoch, 00:00:00 UTC on 1 January 1970), sleep(seconds).
- datetime: the PLS lists datetime objects using the ISO 8601 format '%Y-%m-%d %H:%M:%S': datetime.strptime(text, format) turns text into a datetime, and its strftime(format) turns it back into text.
import math
from copy import deepcopy
print(math.floor(-2.5), math.ceil(-2.5), math.trunc(-2.5), math.fabs(-2.5))
print(math.sqrt(49), math.pow(2, 10), round(math.pi, 4))
original = [[1, 2], [3, 4]]
shallow = original.copy()
deep = deepcopy(original)
original[0][0] = 99
print(shallow[0][0], deep[0][0])Output:
-3 -2 -2 2.5
7.0 1024.0 3.1416
99 1from datetime import datetime
start = datetime.strptime("2026-11-08 09:30:00", "%Y-%m-%d %H:%M:%S")
end = datetime.strptime("2026-11-08 11:05:30", "%Y-%m-%d %H:%M:%S")
print(start.strftime("%H:%M:%S"), start.date(), (end - start).total_seconds())Output:
09:30:00 2026-11-08 5730.0Text files
open(name, mode) with mode 'r' (read, the default), 'w' (write: creates the file or erases it) or 'a' (append to the end). Using with closes the file automatically, even after an error.
- Reading: for line in f, f.readline() (one line; it returns an empty string '' at the end of the file), f.readlines() (a list of all remaining lines).
- Opening a missing file for reading raises FileNotFoundError, so wrap open() in try / except FileNotFoundError when the file may not exist.
- Writing: f.write(text) and f.writelines(list_of_strings). Neither adds a newline: include \n yourself.
- Each line read keeps its newline, so use strip() before split(',').
with open("scores.txt", "w") as f:
f.write("Ana,71\n")
f.writelines(["Ben,64\n", "Cy,88\n"])
with open("scores.txt", "a") as f:
f.write("Dee,59\n")
total = 0
with open("scores.txt", "r") as f:
for line in f:
name, score = line.strip().split(",")
total = total + int(score)
print("Total:", total)
with open("scores.txt") as f:
print(f.readline().strip(), len(f.readlines()))Output:
Total: 282
Ana,71 3Control characters
Text files mark line ends with control characters: LF (line feed, \n), CR (carriage return, \r; Windows files use CR LF) and HT (horizontal tab, \t, used in tab-separated files). strip() removes all of them from the ends of a line.
Worked example
A file temps.txt holds one temperature per line. Write a function that returns their mean, ignoring blank lines.
- ```python with open("temps.txt", "w") as f: f.write("18.5\n\n21.0\n19.5\n") def mean_temperature(filename): values = [] with open(filename) as f: for line in f: line = line.strip() if line: values.append(float(line)) return sum(values) / len(values) print(mean_temperature("temps.txt")) ```
- Output: ``` 19.666666666666668 ```
Answer: strip each line, skip empty strings, convert with float(), then divide the sum by the count.
Check yourself
- What does this program print?
```python
import math
print(math.floor(-3.2), math.ceil(-3.2), math.trunc(-3.2))
```
Show answer
-4 -3 -3. floor rounds down to -4, ceil rounds up to -3, trunc removes the fractional part giving -3. Output: `-4 -3 -3`
- What does this program print?
```python
from copy import deepcopy
a = [[1], [2]]
b = a.copy()
c = deepcopy(a)
a[0].append(5)
print(b[0], c[0])
```
Show answer
[1, 5] [1]. A shallow copy shares the inner lists, so b[0] sees the change; deepcopy copied them, so c[0] does not. Output: `[1, 5] [1]`
- How many lines does this program report?
```python
with open("log.txt", "w") as f:
f.write("a\nb\n")
with open("log.txt", "w") as f:
f.write("c\n")
with open("log.txt", "a") as f:
f.write("d\ne\n")
with open("log.txt") as f:
print(len(f.readlines()))
```
Show answer
3. The second 'w' erases a and b, leaving c. Appending adds d and e, so the file has `3` lines.
- What does this program print?
```python
def price(cost, rate=0.2):
return round(cost * (1 + rate), 2)
print(price(50), price(50, 0.05))
```
Show answer
60.0 52.5. The first call uses the default rate 0.2: 60.0. The second passes 0.05: 52.5. Output: `60.0 52.5`
- What does this program print?
```python
count = 10
def add_one():
count = 1
return count + 1
print(add_one(), count)
```
Show answer
2 10. count inside the function is a new local variable; the global count stays 10. Output: `2 10`
- A program must add today's readings to the end of an existing file without losing earlier data. Which mode should it use?
- 'w'
- 'r'
- 'a'
- 'x'
Show answer
'a'. Append mode writes after the existing content.
- Which call can return any whole number from 1 to 6 inclusive?
- random.randint(1, 6)
- random.randint(0, 6)
- random.random(1, 6)
- random.uniform(1, 6)
Show answer
random.randint(1, 6). randint includes both end points.
- Why is line.strip() used before line.split(',') when reading a file?
- To convert the line to a number
- To remove the newline character at the end of the line
- To remove the commas
- To close the file
Show answer
To remove the newline character at the end of the line. Without strip(), the last field keeps its '\n', so a comparison such as field == 'Ben' fails and printed values carry an extra line break. (int() happens to ignore surrounding whitespace, so int('71\n') still gives 71, but relying on that is fragile.)
Sources
- Pearson Edexcel International Advanced Subsidiary/Advanced Level in Computer Science specification, Issue 1 (March 2026)
- Pearson Edexcel IAL Computer Science Unit 4 Programming Language Subset (PLS)
- Pearson Edexcel IAL Computer Science sample assessment materials (Unit 3 and Unit 4)
Last updated 8 November 2026. Spotted a mistake? Tell us.