Menu

Subprograms

A subprogram is a separate block of code that performs one identifiable task. It has a name, and when the program needs that task doing, it calls the subprogram by name.

When you decompose a problem, you end up with a list of tasks. Each manageable task can be turned into a subprogram, so the code for one job sits together in one place instead of being scattered through the main program. Splitting a program into a main program plus separate blocks of logic is itself decomposition at the code level.

Built-in, library or your own

Subprograms can come from three places.

  • Built into the language, such as len(), which gives the number of items in a list. It is ready to use and you did not write it.
  • Supplied by a library, such as math.sqrt(), which you can call once you have written import math. Someone else wrote it.
  • Written by the programmer in the same program file, using def. This is the block you create for a task your decomposition found.
def isMultipleOf(number, factor):
    # one task: is number a multiple of factor?
    if number % factor == 0:
        return True
    else:
        return False

print(isMultipleOf(21, 7))
print(isMultipleOf(20, 7))

Output:

True
False

Here isMultipleOf does one identifiable job: it works out whether one number is a multiple of another and returns a True or False answer. The main program calls it twice, passing different arguments each time.

The list of tasks from your decomposition has not changed, but the code now shows clearly which block does which job.

Practise this