You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A subroutine is a named block of code that performs a specific task. Subroutines make programs easier to read, test, debug, and maintain. They are a crucial part of GCSE Computer Science (AQA 3.2 / OCR J277 2.2).
A subroutine is a self-contained section of code that can be called (invoked) by name whenever it is needed. Instead of writing the same code multiple times, you write it once as a subroutine and call it whenever required.
There are two types of subroutine:
| Type | Description | Returns a value? |
|---|---|---|
| Procedure | Performs a task but does NOT return a value | No |
| Function | Performs a task and RETURNS a value | Yes |
Exam Tip: The key distinction is that a function returns a value that can be stored in a variable or used in an expression. A procedure simply carries out an action.
A procedure performs an action without returning a value.
SUBROUTINE greet(name)
OUTPUT "Hello, " + name + "!"
ENDSUBROUTINE
greet("Alice")
greet("Bob")
In Python, both procedures and functions are defined with def. A procedure simply has no return statement (or returns None).
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
greet("Bob")
A function performs a task and returns a value using RETURN.
SUBROUTINE calculate_area(length, width)
area ← length * width
RETURN area
ENDSUBROUTINE
result ← calculate_area(5, 3)
OUTPUT result
def calculate_area(length, width):
area = length * width
return area
result = calculate_area(5, 3)
print(result) # 15
Key Point: After a
returnstatement executes, the function immediately stops and sends the value back to the caller.
def multiply(a, b): # a and b are parameters
return a * b
result = multiply(4, 7) # 4 and 7 are arguments
Subroutines can accept any number of parameters:
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
return round(bmi, 1)
print(calculate_bmi(70, 1.75)) # 22.9
flowchart TD
A[Subroutine called] --> B{Does it RETURN a value?}
B -->|No| C[Procedure]
C --> D[Performs an action]
D --> E["Control returns to caller<br/>no value passed back"]
B -->|Yes| F[Function]
F --> G[Computes a value]
G --> H[RETURN value to caller]
H --> I["Value used in expression<br/>or stored in variable"]
| Benefit | Explanation |
|---|---|
| Decomposition | Break a large problem into smaller, manageable sub-problems |
| Reusability | Write once, call many times — avoids duplicating code |
| Readability | The main program reads like a series of clearly named steps |
| Testing | Each subroutine can be tested independently |
| Maintainability | Fix a bug in one place instead of hunting through repeated code |
| Teamwork | Different team members can work on different subroutines |
A local variable is declared inside a subroutine and can only be used within that subroutine. It is created when the subroutine runs and destroyed when it ends.
def calculate_tax(amount):
tax = amount * 0.2 # tax is local
return tax
print(calculate_tax(100)) # 20.0
# print(tax) ← This would cause an error — tax does not exist here
A global variable is declared outside all subroutines and can be accessed from anywhere in the program.
total_score = 0 # global variable
def add_score(points):
global total_score
total_score += points
add_score(10)
add_score(5)
print(total_score) # 15
Scope refers to where in a program a variable can be accessed:
| Scope | Where declared | Where accessible |
|---|---|---|
| Local | Inside a subroutine | Only within that subroutine |
| Global | Outside all subroutines | Anywhere in the program |
Exam Tip: Examiners expect you to understand that local variables are preferred because they prevent accidental changes from other parts of the program. Using global variables excessively is considered poor practice.
Programming languages provide many built-in functions. You have already used some:
| Function | Purpose | Example |
|---|---|---|
len() | Returns the length of a string or array | len("hello") → 5 |
int() | Converts to integer | int("42") → 42 |
str() | Converts to string | str(99) → "99" |
float() | Converts to float | float("3.14") → 3.14 |
input() | Reads user input | input("Name: ") |
print() | Displays output | print("Hello") |
round() | Rounds a number | round(3.456, 1) → 3.5 |
A program that uses subroutines to calculate and display a student's grade:
def get_mark():
mark = int(input("Enter mark (0-100): "))
return mark
def calculate_grade(mark):
if mark >= 90:
return "A*"
elif mark >= 80:
return "A"
elif mark >= 70:
return "B"
elif mark >= 60:
return "C"
else:
return "U"
def display_result(mark, grade):
print(f"Mark: {mark}, Grade: {grade}")
# Main program
mark = get_mark()
grade = calculate_grade(mark)
display_result(mark, grade)
return — writing a function that prints a result instead of returning it.calculate_area(5, 3) without assigning it to a variable.RETURN.The program below decomposes the problem of marking a short quiz into three subroutines: reading answers, checking answers, and printing results.
CORRECT_ANSWERS = ["B", "A", "C", "D", "A"]
def read_answers():
answers = []
for i in range(len(CORRECT_ANSWERS)):
response = input(f"Q{i + 1}: ").upper()
answers.append(response)
return answers
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.