Edexcel International Advanced Level Computer Science, point 9.1.3
Modularity (9.1.2) means building a program from separate parts. This page covers the features of the language you use to do it. Check the Programming Language Subset (PLS) and the Good Programming Practice Guide (GPPG) for the exact detail.
a. Blocked code
A block is a group of statements that belong together, such as the body of an if, a loop or a subprogram. In Python, indentation defines the block.
# the block below belongs to the loop
for number in numbers:
if number % 2 == 0: # this block belongs to the if
print(number, "is even")
else:
print(number, "is odd")
print("Done") # back at the outer level
- Indent consistently (4 spaces is standard).
- Keep blocks short, so that each can be understood at a glance.
- Deeply nested blocks are hard to read (9.2.3).
b. User-defined subprograms
Subprograms you write yourself (7.1.4):
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
print(celsius_to_fahrenheit(100)) # 212.0
- One job each, with a clear name.
- Parameters in, return value out.
c. Built-in subprograms
Subprograms that come with the language, so you don't need to write them.
| Built-in | Job |
|---|---|
len(), sum(), min(), max() |
Measure and summarise collections |
sorted(), reversed() |
Order items |
range(), enumerate(), zip() |
Support loops |
int(), float(), str() |
Convert types |
print(), input(), open() |
Input and output |
abs(), round(), pow() |
Numeric operations |
Using built-ins is good practice: they are tested, optimised and well understood, so don't rewrite them (apart from learning how they work).
marks = [60, 45, 82]
print(sum(marks) / len(marks), max(marks), sorted(marks))
d. Libraries of subprograms
A library (or module) is a collection of ready-made subprograms and constants, loaded with import.
import math
import random
from datetime import date
print(math.sqrt(49)) # 7.0
print(random.randint(1, 6))
print(date.today())
import mathand thenmath.sqrt(): names are kept in the module's namespace, which avoids clashes.from math import sqrtlets you writesqrt()directly.- Common standard libraries:
math,random,datetime,sqlite3,json,re. - Third-party libraries (such as NumPy and Pandas, 18.1) are installed separately.
- Benefits: save time, reliable, well documented.
- Drawbacks: dependency on the library, and you must learn it.
e. Files
Your own code can be split across several files (modules), each holding related subprograms. Another file imports them.
File shapes.py:
PI = 3.14159
def circle_area(radius):
return PI * radius ** 2
def rectangle_area(width, height):
return width * height
File main.py:
import shapes
print(shapes.circle_area(2)) # 12.56636
print(shapes.rectangle_area(3, 4)) # 12
- Files are grouped by purpose (
input_output.py,calculations.py,database.py). - The main file stays short, and reads like a list of steps.
- Code in a file can be reused by other programs.
- Tip: put the starting code under
if __name__ == "__main__":, so that importing a file doesn't run its main program.
f. Procedures and g. Functions
| Procedure | Function | |
|---|---|---|
| Returns a value? | No | Yes |
| Use for | An action (display, save, update) | A calculation that gives back a result |
| Example | show_menu() |
average(marks) |
Good practice: use functions for calculations (so they can be tested and reused), and procedures for actions with side effects (output, saving). Name them to match: verbs for procedures (show_menu), nouns or questions for functions (average, is_valid).
Modular design in practice
Benefits: each file can be tested alone, several people can work on different files, and a change in one doesn't affect the others as long as the interface stays the same.
Worked example
Task: restructure a "temperature converter" so that it is modular, using the features above.
# converter.py (library of the program's own subprograms)
def get_unit(): # user-defined function
while True:
unit = input("Convert from C or F? ").strip().upper()
if unit in ("C", "F"):
return unit
print("Please type C or F")
def convert(value, unit): # user-defined function
if unit == "C":
return value * 9 / 5 + 32 # Celsius to Fahrenheit
return (value - 32) * 5 / 9 # Fahrenheit to Celsius
def show_result(value, unit, result): # procedure
other = "F" if unit == "C" else "C"
print(f"{value}{unit} is {round(result, 1)}{other}")
# main.py
import converter # file used as a library
unit = converter.get_unit()
value = float(input("Temperature: "))
converter.show_result(value, unit, converter.convert(value, unit))
- Blocked code: each
ifandwhilehas its own indented block. - User-defined subprograms:
get_unit,convert,show_result. - Built-in subprograms (
input,float,round,print) and a library file (import converter). - Function (
convert: returns a value) and procedure (show_result: only displays).
Exam tip: be able to name and describe each feature (block, user-defined subprogram, built-in, library, file, procedure, function) and give an example from code. Say why each helps modularity: reuse, testing, readability, teamwork. Use import correctly.
Check yourself
How are blocks of code shown in Python?
By indentation: statements indented to the same level belong to the same block.
What is the difference between a built-in subprogram and a library?
A built-in subprogram comes with the language and is always available (such as len). A library is a collection of subprograms that must be imported (such as math).
Why split a program across several files?
Related code is grouped together, files can be tested and reused separately, and teams can work on different files.
When should you use a function instead of a procedure?
When the subprogram calculates a result that needs to be returned to the caller.