Sub Programs
A sub program is a named block of code that you write once and then run whenever you need it. Writing it is called defining it; asking it to run is called calling it.
defA definition starts with the keyword def, then the sub program's name, then a pair of brackets, then a colon. The code that does the work goes on the lines underneath and must be indented, usually by four spaces.
Those indented lines are the body of the sub program. Python has no end keyword, so the body finishes at the first line that is no longer indented, which belongs to the main program again. Defining a sub program does not run it — the body only runs when a call is made.
To run the sub program, write its name followed by brackets. Those brackets still have to be written when the sub program takes nothing in, so you write showBanner() and never showBanner. Without brackets, Python treats the name as an ordinary variable rather than a call, so the body never runs.
# a definition: def, name, brackets, colon, indented body
def showBanner():
print("*** School Quiz Night ***")
print("Friday, 7pm, Main Hall")
# main program: each call is the name plus brackets
showBanner()
print("Teams of four - bring a pencil")
showBanner()Output:
*** School Quiz Night ***
Friday, 7pm, Main Hall
Teams of four - bring a pencil
*** School Quiz Night ***
Friday, 7pm, Main Hall
Python is case-sensitive, so the name in the call must match the definition exactly, capitals included. ShowBanner() is a different name from showBanner(), so Python cannot find that definition and reports a NameError.
Python reads the file from top to bottom, so the definition must be reached before the call runs. That is why definitions are usually placed above the main program, with the calls below them.
OCR GCSE Computer Science · Sub Programs