Menu

Libraries

Procedures and Functions

A subprogram is a named block of code that you call when you need it. Subprograms come in two kinds, and the difference between them is what the call hands back.

Procedures do a job

A procedure carries out a task but does not return a value. You call it for what it does, not for what it gives back. A procedure that adds an item to a list shows this clearly — scores.append(3) changes the list, and that is the end of it; nothing is handed back to store or calculate with.

Functions hand a value back

A function is a subprogram that returns a value to the point in the program where it was called. The call is swapped for that value, exactly as if you had typed the value yourself, so the rest of the line carries on with it. len("marble") returns 6, which is why len("marble") * 3 works out 18. round(7.6) returns 8, and str(25) returns the text "25"; returned values like these can be stored or used straight away.

A function call len("marble") * 3 sends a call to the function and gets 6 back, giving 18. A procedure call scores.append(3) does its job and nothing comes back.

CallProcedure or functionWhat happens
scores.append(3)Procedure3 is added to the list; no value comes back
len("marble")Function6 comes back to the point of the call
round(7.6)Function8 comes back
str(25)FunctionThe text "25" comes back

Using a returned value

A returned value is not shown on screen by itself. If nothing is done with it, it is lost and the program simply moves on. You can store it in a variable, print it, or use it straight away in a calculation.

sport = "tennis racket"
points = len(sport) * 2
points_text = str(points)
print(points_text)

Output:

26

Here len(sport) returns 13, and that number is used in the calculation of points. str(points) returns 26 as text, which is stored in points_text. print(points_text) then displays that text as a procedure, returning nothing to the program. A line containing only len(sport) would count the letters and throw the count away.

Practise this