Functions
In Python 3, a subprogram is a named block of code that you write once and can run whenever you need it. You define one using the def keyword, followed by the name you choose, a parameter list in round brackets, and a colon. Everything the subprogram does goes underneath, indented so Python knows it belongs to the definition.
The indented lines are called the body. They do not run when Python reads the def line; they run only when something calls the subprogram by name.
A function is a subprogram whose definition includes a return statement. The return statement does two things at once: it sends a value back to whoever called the function, and it ends the function immediately, so any lines after it in the body are skipped. A procedure is a subprogram with no return statement, so it carries out a task and hands nothing back. If you leave the return out, the subprogram is a procedure, and calling it gives you no value to store or print.
Printing is not returning. A procedure that prints a message has still returned no value, so it is a procedure, not a function.
def showTeam(sport):
print("Your sport is " + sport)
print("Good luck in the match")
def doubleScore(score):
return score * 2
showTeam("hockey")
points = doubleScore(14)
print(points)Output:
Your sport is hockey
Good luck in the match
28
A function is allowed to contain several return statements, but only one of them can run on any particular call. This is handy when you want different results for different inputs: put each return inside a branch, so only the branch that matches is reached.
def describeTemperature(degrees):
if degrees < 5:
return "freezing"
elif degrees < 18:
return "cool"
return "warm"
print(describeTemperature(2))
print(describeTemperature(12))
print(describeTemperature(25))Output:
freezing
cool
warm
Calling the function with 2 stops at the first return, so the lines below it are skipped. Calling it with 25 fails both tests and falls through to the last return. The order of the branches matters: once a return has run, no later one can.
Edexcel GCSE Computer Science · Functions