Home / GCSE · AQA / Computer Science / Programming

CS9Subroutines and Structured Programming

3.2.10 Subroutines

What a subroutine is

AQA's definition: a subroutine is “a named ‘out of line’ block of code that may be executed (called) by simply writing its name in a program statement.” It can be reused many times in a program.

  • Out of line means the code is written in one place, usually at the top of the program, away from the main sequence of steps.
  • Defining a subroutine doesn't run it. Nothing happens until the subroutine is called by name.
  • When it is called, the program jumps to the subroutine, runs its code, then comes back and carries on from the line after the call.
  • AQA pseudo-code:
    SUBROUTINE showRules()
        OUTPUT 'Guess a number from 1 to 50'
        OUTPUT 'You have six tries'
    ENDSUBROUTINE
    
    showRules()
  • Python:
    def showRules():
        print("Guess a number from 1 to 50")
        print("You have six tries")
    
    showRules()
  • You already use subroutines that someone else wrote: len(), print(), input() and randrange() are all subroutines.
  • “Subroutine” is the general word. The two kinds are procedures and functions.

A call jumps to the subroutine; when it finishes, the program carries on from the call.

Subroutine
A named ‘out of line’ block of code that may be executed (called) by simply writing its name in a program statement. It can be reused many times in a program.
Call
Running a subroutine by writing its name (and any parameters) in a program statement.
3.2.10 Subroutines

Procedures and functions

  • In AQA's pseudo-code, a subroutine that contains RETURN is a function. One without RETURN is a procedure.
  • In Python, a subroutine with return followed by a value is a function. Both kinds start with def.
  • A procedure just does something, such as output a message. A function works something out and sends a value back.
  • AQA pseudo-code:
    SUBROUTINE greet(name)
        OUTPUT 'Hello ' + name
    ENDSUBROUTINE
    
    SUBROUTINE square(n)
        RETURN n * n
    ENDSUBROUTINE
  • Python:
    def greet(name):
        print("Hello " + name)
    
    def square(n):
        return n * n
    
    greet("Zara")           # Hello Zara
    print(square(7))        # 49
  • Call a procedure on its own line: greet('Zara'). Use a function's call where you need its value: area ← square(7).
ProcedureFunction
Contains RETURN with a value?NoYes
What it gives backNothingOne value, to the calling code
How it is calledgreet('Zara')result ← square(7)
Procedure
A subroutine that does not return a value (no RETURN in AQA's pseudo-code).
Function
A subroutine that returns a value to the code that called it (it contains RETURN).
3.2.10 Parameters

Parameters: passing data in

Parameters are variables which define the data to be passed into a subroutine when it is called.

  • The parameters are listed in brackets in the subroutine's first line: def showBill(item, price, qty):.
  • When the subroutine is called, each value goes into the parameter in the same position: the first value into the first parameter, and so on.
    def showBill(item, price, qty):
        total = price * qty
        print(f"{qty} x {item}: £{total}")
    
    showBill("Pen", 2, 4)       # 4 x Pen: £8
    showBill("Ruler", 3, 2)     # 2 x Ruler: £6
  • The values can be variables or expressions: showBill(choice, cost, 3).
  • The number of values in the call must match the number of parameters. showBill("Pen", 2) causes an error: there is nothing to go into qty.
  • Parameters let one subroutine work on different data each time it is called, so it can be reused.
  • Strictly, the values in the call are “arguments”. AQA uses “parameter” for both, and so do exam questions.
Exam tipIn one AQA paper only 40% of students could name a subroutine's parameter. The parameters are the names in brackets in the subroutine's first line, such as item, price and qty.
Parameter
A variable which defines data to be passed into a subroutine when it is called. AQA also uses the word for the values passed in.
3.2.10 Return values

Return values: passing data out

  • RETURN (Python return) sends a value back to the code that called the subroutine.
  • The calling code must use that value: store it, output it, or put it in an expression.
    def areaOfRectangle(width, height):
        area = width * height
        return area
    
    result = areaOfRectangle(4, 7)
    print(result)                      # 28
  • Return is not output. print() shows a value on the screen, but the calling code can't use it. return passes the value to the calling code, but shows nothing.
  • A Python function with no return gives back None:
    def doubleIt(n):
        print(n * 2)
    
    x = doubleIt(5)       # prints 10
    print(x)              # None: nothing was returned
  • return ends the subroutine straight away. Any lines after it in that path don't run.
  • A subroutine can return the value of a variable or an expression: RETURN width * height.
Exam tipRead the question's verb. “Return the total” needs return total. “Output the total” needs print(total). Examiners give no credit for printing a value that should be returned, or the other way round.
Return value
The value a function passes back to the code that called it.
3.2.10 Subroutines

Calling subroutines and using the result

  • A function call stands for the value it returns, so it can go anywhere a value can.
  • In an assignment: answer ← add(2, 3) * 6 gives 30: add(2, 3) returns 5, then 5 × 6 is worked out.
  • In a condition: IF square(n) > 100 THEN.
  • In output: print(areaOfRectangle(2, 3) + areaOfRectangle(1, 5)) outputs 11.
  • Calls inside calls: the inner call is worked out first. square(add(1, 2)) is square(3), which is 9.
  • Each call is separate: the function starts again with the new parameter values.
  • Python:
    def add(a, b):
        return a + b
    
    def square(n):
        return n * n
    
    answer = add(2, 3) * 6
    print(answer)                  # 30
    print(square(add(1, 2)))       # 9
    if square(4) > 10:
        print("Big")               # Big
Worked exampleSUBROUTINE f(x) returns x * 2 + 1. What does OUTPUT f(3) + f(f(1)) output?
  1. f(3) = 3 × 2 + 1 = 7first call
  2. f(1) = 1 × 2 + 1 = 3inner call of f(f(1)) first
  3. f(3) = 7the outer call gets 3
  4. 7 + 7 = 14add the two returned values
14
Exam tipDon't write over = gameOver() once and then keep testing over in a loop: the variable won't change on its own. Call the function each time you need a fresh answer, for example in the loop condition: while not gameOver():.
Calling routine
The code that called a subroutine, which receives any value it returns.
3.2.10 Local variables

Local variables

Subroutines can declare their own variables, called local variables. AQA says local variables usually only exist while the subroutine is executing and are only accessible within the subroutine.

  • A variable created inside a subroutine is local to it. Its parameters behave the same way.
  • When the subroutine finishes, its local variables are gone. To keep a result, return it and store it in the calling code.
    def average(a, b, c):
        total = a + b + c
        return total / 3
    
    mean = average(6, 9, 12)
    print(mean)       # 9.0
    print(total)      # NameError: total only existed inside average
  • Why use local variables?
  • Two subroutines can each use a variable called count without clashing or changing each other's value.
  • The subroutine is self-contained, so it can be reused in another program or tested on its own.
  • The memory a local variable uses is freed when the subroutine ends.
  • Nothing outside the subroutine can change its local variables by accident, so errors are easier to find.
  • The opposite is a global variable, created in the main program and usable everywhere. You don't need to know more about globals for this course.

Inside the subroutine: local. Outside: it doesn't exist.

Exam tipExaminers report students using a function's local variable after the call, as if it still existed. Store the returned value instead: mean = average(6, 9, 12).
Local variable
A variable declared within a subroutine. It exists only while the subroutine is executing and is accessible only from within the subroutine.
Global variable
A variable declared in the main program that can be used anywhere in the program.
3.2.10 Subroutines

Advantages of subroutines

  • Reuse: write the code once and call it as many times as needed, so the program is shorter.
  • One place to change: to fix or improve the code, you edit the subroutine once and every call uses the new version.
  • Testing: each subroutine can be tested on its own, so errors are easier to find.
  • Easier to read: a well-named call such as showScore(score) tells the reader what happens without the detail.
  • Teamwork: different programmers can write different subroutines at the same time.
  • Decomposition: each sub-problem of a big problem can become its own subroutine.
  • Libraries: tested subroutines can be shared and used in other programs.
Exam tip“Explain” needs the reason, not just the label. “Easier to test” is a start; “each subroutine can be tested on its own, so errors are easier to find” earns the full mark. Words such as easier or faster need a why.
Reuse
Calling the same subroutine many times, or using it in other programs, instead of rewriting its code.
3.2.10 Structured programming

The structured approach to programming

AQA's definition: the structured approach to programming includes modularised programming, clear, well-documented interfaces (local variables, parameters) and return values.

  • Modularised programming: the program is split into modules (subroutines), each doing one identifiable task.
  • Interface: how a subroutine is used from outside: its identifier, its parameters and its return value.
  • Clear, well-documented interface: meaningful names; all the data it needs comes in through parameters; its result goes out through a return value; it uses local variables; comments say what it does and what each parameter means.
  • A documented interface in Python:
    def lateFee(daysLate, dailyRate):
        # Returns the fine, in pounds, for one overdue library book
        # daysLate: whole days overdue; dailyRate: fine per day in pounds
        if daysLate <= 0:
            return 0
        fee = daysLate * dailyRate
        return fee
    
    print(lateFee(4, 0.25))     # 1.0
    print(lateFee(0, 0.25))     # 0
  • Advantages of the structured approach: programs are easier to understand, test, debug and maintain; modules can be reused; programmers can work on different modules at the same time.
Characteristics (what it is)Advantages (why it helps)
Modularised: one task per subroutineEach module can be tested on its own
Clear interfaces: parameters in, return values outModules can be reused in other programs
Local variables inside each moduleNo clashes between modules' variable names
Meaningful names and commentsEasier for others to read and maintain

A program broken into modules, each with a clear interface.

Exam tipUnder 10% of students gave two characteristics when asked for them: most gave advantages instead. If the question says characteristics, describe what a structured program looks like. If it says advantages or benefits, say why that helps.
Structured approach
Programming using modularised programming, clear well-documented interfaces (local variables, parameters) and return values.
Interface (of a subroutine)
How a subroutine is used from outside: its identifier, parameters and return value.
Module
A self-contained part of a program, such as a subroutine, that does one identifiable task.
3.2.10 Subroutines

Writing a subroutine to an exam brief

  • Use the identifier the question gives, exactly.
  • Put the parameters in the order the question gives them.
  • If a value arrives as a parameter, don't input it again inside the subroutine.
  • Return or output, exactly as the question says.
  • Set up counters and totals inside the subroutine, so they are local and start again on every call.
  • If asked, write the calling code too: get the values, call the subroutine, and use what it returns.
  • Tick off each bullet point in the question as you cover it.
Worked exampleWrite a Python function areaOfCircle that takes a radius as a parameter and returns the area, using a constant PI = 3.142. Then input a radius, call the function and output the result.
  1. PI = 3.142a named constant, in capitals
  2. def areaOfCircle(radius):the identifier and parameter from the question
  3. area = PI * radius * radius
    return area
    local variable; return, not print
  4. r = float(input("Radius: "))the radius can be a real number
  5. print(areaOfCircle(r))call it and output the returned value
For a radius of 2, the program outputs 12.568.
Exam tipWriting the subroutine's first line correctly (def, the right identifier, the right parameters) usually earns a design mark on its own, even if the rest has errors. Always attempt it.
Subroutine header
The first line of a subroutine, giving its identifier and parameters, such as def areaOfCircle(radius):