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.

Practise this in the app: instant marking and a fix for every mistake. Free, no email needed to start.

Practise this lesson

Subprograms

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:

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

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

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 3

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

  1. ```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")) ```
  2. Output: ``` 19.666666666666668 ```

Answer: strip each line, skip empty strings, convert with float(), then divide the sum by the count.

Key idea: Functions return values, procedures do not; prefer parameters and return values to globals. import modules; math, random, copy, time from the PLS. Files: 'r', 'w' (erases), 'a'; with closes the file; strip() before split().

Check yourself

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

  2. 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]`

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

  4. 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`

  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`

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

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

  8. 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.)

Practise with instant feedback

Sources

Last updated 8 November 2026. Spotted a mistake? Tell us.