Sub Programs
Choosing between a function and a procedure depends on whether the code that calls it needs a value back. A function is the right choice when the calling code needs a result to use, such as a calculation, a true/false check, or a value to store in a variable. A procedure is the right choice when the task only needs to do something, such as displaying output, and no value needs to be returned.
A function must send its result back with return. Printing the result inside the function is not the same: the caller has no returned value to store or use. If a function works out the area of a board, it should return the area so the main program can store it or compare it. If a procedure shows a menu on screen, printing is the whole job, so there is nothing to return.
def board_area(length, width):
return length * width
def show_menu():
print("Start game")
print("Quit game")
area = board_area(5, 3)
print(area)
show_menu()Output:
15
Start game
Quit game
| What the caller needs | Choose | Reason |
|---|---|---|
| A number for another calculation | Function | The caller needs the result |
True or False for an if condition | Function | The returned Boolean is the check |
| A value to store in a variable | Function | The returned value can be assigned |
| A menu shown on screen | Procedure | Displaying is the whole task |
| The basket total display updated after an item is scanned | Procedure | No result is needed back |
In Python, practical uses include a calculation function, a conversion function, a grading function, a procedure that displays instructions, and a quiz app decomposed into sub programs, with a procedure that shows the current question and a function that checks whether the chosen answer is correct.
OCR GCSE Computer Science · Sub Programs