OCR H446, section 2.1.3 (d)
A sub-procedure (a subroutine: a function or a procedure) is a named, self-contained part of a program that does one specific job. Splitting a solution into sub-procedures is the procedural way of dealing with complexity.
Why use sub-procedures?
- Easier to understand: each part is small and has a clear purpose.
- Easier to write: a problem is solved one piece at a time.
- Easier to test: each one can be tested on its own.
- Reuse: call it from many places (2.1.2 (d)).
- Less repetition: shorter code, and a fix needs to be made once.
- Teamwork: different people write different parts.
- Easier to maintain: change one without touching the others.
Functions and procedures
| Function | Procedure | |
|---|---|---|
| Returns a value? | Yes | No |
| Used | In an expression: x = square(4) |
As a statement: show_menu() |
How to identify sub-procedures
- Start with the whole task stated in one sentence.
- Split into major steps (what must happen).
- Split each step into smaller steps until each is one clear job.
- Look for repeated actions, which should be the same sub-procedure.
- Decide the inputs (parameters) and outputs (return value) of each.
- Draw them as a hierarchy chart (structure diagram).
Good sub-procedures have
- High cohesion: they do one job and all their code relates to it.
- Low coupling: they depend little on other parts, and communicate through parameters and return values, not global variables.
- A meaningful name that says what they do (
calculate_total, notthing2). - Documentation of purpose, parameters, return value and preconditions.
Hierarchy chart
A hierarchy chart shows the top-level task at the top, broken down into sub-procedures below:
Read it top-down. The chart shows what the parts are and how they relate, not the order they run in.
Parameters and return values
- Parameters pass data into a sub-procedure.
- A function returns a value out.
- Local variables exist only inside the sub-procedure (2.2.1 (c)).
def check_answer(given, correct):
"""Return True if the answer is right."""
return given.strip().lower() == correct.lower()
Worked example
Task: a program lets a teacher enter marks for a class, then shows the mean, the highest mark, and how many students passed (50 or above). Split it into sub-procedures.
| Sub-procedure | Type | Job | Parameters | Returns |
|---|---|---|---|---|
get_marks |
function | Ask for the marks and validate each | none | list of marks |
mean |
function | Calculate the average | marks |
the mean |
highest |
function | Find the largest | marks |
the highest mark |
count_passes |
function | Count marks of 50 or more | marks |
the count |
show_report |
procedure | Display the results | mean, highest, passes | nothing |
| main program | Calls the above in order |
def get_marks():
marks = []
n = int(input("How many students? "))
while n < 1:
n = int(input("At least 1 student: "))
for _ in range(n):
m = int(input("Mark: "))
while m < 0 or m > 100:
m = int(input("Mark must be 0 to 100: "))
marks.append(m)
return marks
def mean(marks):
return sum(marks) / len(marks)
def highest(marks):
return max(marks)
def count_passes(marks):
return len([m for m in marks if m >= 50])
def show_report(avg, top, passes):
print(f"Mean: {avg:.1f}")
print(f"Highest: {top}")
print(f"Passes: {passes}")
marks = get_marks()
show_report(mean(marks), highest(marks), count_passes(marks))
Each part is small, has one job, and uses parameters and return values, so it can be tested separately and reused: mean could be used in a different program.
Exam tip: name the sub-procedures from the scenario, say what each one does, and what it takes in and returns. Use the terms cohesion and coupling when you explain why the split is good. Don't confuse the hierarchy chart (structure) with a flowchart (order of steps).
Check yourself
What is a sub-procedure?
A named, self-contained part of a program that does one specific job. It is a function or a procedure.
Give three advantages of splitting a program into sub-procedures
Any three of: easier to understand, write and test; code can be reused; less repetition; teams can work on different parts; easier to maintain.
What is the difference between a function and a procedure?
A function returns a value to the code that called it. A procedure does not.
What does a hierarchy chart show?
How a task is broken down into sub-procedures, with the top-level task at the top and the smaller parts below it.