Every root-finding script in Control Flow and Simple Numerical Programs was a one-off: change
x at the top, rerun the whole file. That approach does not scale — a real program needs to compute a bisection square root and an implied volatility and a bond yield, in the same run, on different inputs, without copy-pasting the loop three times. Functions are Python's mechanism for packaging a piece of logic once and reusing it under many different inputs, and decomposition — breaking a program into functions with clear input–output contracts — is the single most important design habit this unit teaches. This note covers how functions are defined and called, what happens to parameters when a function runs, and Python's scoping rules, which govern which names a piece of code can see.Learning objectives. By the end of this note you should be able to:
- define a function with
def, including positional parameters, keyword arguments, and default values, and correctly predict the values bound on a given call; - trace what a
returnstatement does to the flow of execution, and state what a function returns when it has noreturnstatement; - explain Python's scoping rule (a name assigned anywhere in a function body is local to that function) and predict when this causes an
UnboundLocalError; - rewrite one of the previous topic's root-finding scripts as a well-parameterised, reusable function.
In this lesson
- Defining and calling functions
- Keyword arguments and default values
- Scoping
- Packaging a root-finder as a function
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.