Menu

Functions

Benefits of Subprograms

A subprogram is a named block of code that does one job and is called whenever that job is needed. Writing your program this way has real benefits, and they all come from the fact that the code for a task exists in exactly one place.

No duplicated code

Without a subprogram you would copy the same lines every time you needed them. A quiz program that works out a percentage after every round might repeat the same five lines for round 1, round 2 and round 3. Put that calculation in a subprogram called percentage() and you call it three times instead. If the formula changes, you edit one place, not three, so there is no chance of the copies drifting apart and producing different answers.

Easier to read, test, debug and maintain

  • Read: a call such as show_score() tells you what happens without you wading through the detail, so the main program reads like a plan.
  • Test: you can run one subprogram on its own with chosen values and check the result before it is wired into the rest.
  • Debug: when an answer is wrong you can narrow the search to the subprogram responsible rather than scanning the whole program.
  • Maintain: improving or fixing a task means changing one definition, and every call picks up the new version.

Each of these works because a subprogram has a single clear job, with clear inputs and a clear outcome.

def marks_out_of_ten(score, total):
    return round(score / total * 10)

# the same function used for three different tests
print(marks_out_of_ten(18, 20))
print(marks_out_of_ten(7, 10))
print(marks_out_of_ten(45, 50))

Output:

9
7
9

Reuse and libraries

A tested subprogram can be dropped into a completely different program, which saves writing and re-testing it. Collections of these are stored in libraries, and once a library is imported you can call its subprograms whenever you need them.

Practise this