Organising logic.
WHAT A FUNCTION IS
A named block of code you can call, optionally with inputs, optionally returning a result.
WHY USE THEM
Avoid repeating yourself Name a piece of logic Test pieces independently Keep code readable
WHEN TO CREATE ONE
When logic is used more than once When a block needs a name to be understood When a piece of code does one identifiable thing
WHAT MAKES A GOOD FUNCTION
It does one thing Its name says what that is It is short enough to read at once It does not depend on hidden state
ARGUMENTS
Values passed in.
Python supports required arguments, optional ones with defaults, and named arguments.
A COMMON TRAP
Using a changeable value such as a list as a default argument.
The same object is reused across calls, which surprises everyone once.
RETURNING VALUES
A function returns a value, or nothing.
Be consistent: a function returning a value in some paths and nothing in others is difficult to use.
WHAT TO AVOID
Functions with many arguments Functions doing several unrelated things