Functions
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.
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.
show_score() tells you what happens without you wading through the detail, so the main program reads like a plan.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
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.
Edexcel GCSE Computer Science · Functions