Loading...
A subroutine gives a task a name and an interface. Distinguish the values supplied to it, the work it performs and the result returned to its caller.
What you'll be able to do
A subroutine is a named block of code called when its task is needed. Decomposing a program into cohesive tasks reduces duplication and allows each part to be understood and tested separately. Its interface states the inputs, outputs and relevant conditions.
A procedure is commonly described as performing an action, while a function produces a result; exact language terminology varies. A routine can return several logical values, for example as a tuple in Python. Give it a descriptive name that explains its purpose rather than the line number where it appears.
Formal parameters are the names in the definition. Actual arguments are the values or expressions supplied in a call. Their positions or keyword names determine which value is bound to which parameter. Trace a call by evaluating its arguments before following the routine’s body.
Avoid hidden dependence on unrelated globals when explicit parameters would express the required data. Specify valid inputs, such as a non-zero divisor or a non-empty collection. Parameters make a routine reusable, but reusability still depends on what assumptions and side effects its interface exposes.
A return statement transfers a result and control back to the caller. Printing displays text but does not supply that printed value as the function’s result. In Python, a function that reaches its end without an explicit return produces None.
Returning a computed value makes it available for further calculation, testing or a different display interface. A routine can also have side effects, such as changing an object or writing a file; document these rather than disguising them as an ordinary numerical result. Use a small example to verify the connection between a call and its assignment.
def rectangle_area(width, height):
return width * height
area = rectangle_area(4, 7)
print(area)Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.