AQA Computer Science GCSE
Programming Concepts - Subroutines
Subroutines are an example of decomposition - a way of breaking a program down into smaller steps.
This is a key way to write better programs which are easier to write and test - and so are more likely to work better. It's also much easier to reuse sections of code from other programs if you're using well designed subroutines.
There are advantages and disadvantages of using subroutines to decompose a program (although in general they are considered a "good thing" they do make some things a little trickier to achieve in a program using lots of variables).
Advantages and Disadvantages of using Decomposition - this is the same set of bullet points using on the algorithms page
Using Subroutines in Programs
Subroutines are called functions in Python.
To use a subroutine it has to be written first and given a name. It can then be "called" from another part of the program using the name. Values can be sent to the subroutine (technically: parameters are passed to the subroutine) and a single value can be returned from the subroutine to the main program.
Subroutines need to be defined at the top of a Python program.
In this subroutine:
- the name of the subroutine is areaOfCircle()
- the parameter radius is passed to the subroutine
- the value of theArea is calculated
- and then returned to the main program
The code in the main program to call a subroutine works like this:
circumferenceOfCircle(radius) # call a subroutine with a parameter but without assigning the value returned
area <- areaOfCircle(radius) # assign the value returned to a variable
The ways in which variables work in subroutines is tricky and is explained below.
In Python things are a little different, but essentially work the same way.
def areaOfTriangle(aBase, aHeight):
#calling the function from the program
area = areaOfTriangle(base, height)
The function above uses two parameters. As always with Python, watch the indents.
Local and Global Variables
Variables are named areas of computer memory where data items can be stored.
Subroutines use variables. Sometimes those variables are declared (created) inside the subroutine - e.g. a variable to store the answer to one part of a calculation. There are called local variables.
Local variables cause some problems for programmers. In particular, they cannot be used anywhere other than in the subroutine. If you try and use it somewhere else, say in the main program, this will cause an error. They have a "local scope" - they are limited to the subroutine.
Global variables, on the other hand, are declared in the main program and can be used anywhere in the program - including inside subroutines. They have a "global scope".