Python — functions, scope and exceptions
Be able to write functions with default values, understand scope, and handle exceptions with try/except.
Prerequisites
Intuition
A function is a contract: arguments go in, a return value comes out. Three things that separate beginner code from good code:
- Default values:
def train(data, epochs=10, lr=0.01)— the caller only has to give what deviates. - Scope: variables inside the function exist only there. A function that changes global variables is hard to test — return instead.
- Exceptions: when something does not work (a missing file, the wrong type) the function should say so with
raise, not return −1 and hope somebody checks.
Code
def mean(values, *, ignore_empty=False):
"""The mean. An empty list is an error unless ignore_empty=True (then 0.0)."""
if not values:
if ignore_empty:
return 0.0
raise ValueError("an empty list has no mean")
return sum(values) / len(values)
print(mean([1, 2, 3])) # 2.0
print(mean([], ignore_empty=True)) # 0.0
try:
mean([])
except ValueError as e:
print("error:", e)
x = 10
def f():
x = 5 # local — the global one is untouched
return x
print(f(), x) # 5 10
The * in the signature forces ignore_empty to be given by name — which makes the calls readable.
Mastery means
- Writes functions with default values and keyword arguments
- Explains scope: local vs global
- Handles exceptions with try/except and raises its own
Sign in to do the exercises and build your mastery up.
Sources
Leads to
Part of the goals (17)
- The developer's toolbox
- The mathematics behind the models
- Systems knowledge for AI engineers
- Build an agent you can trust
- Frontier Lab — an independent research project
- Train an agent with reward
- Build a transformer from scratch
- Evals in practice
- Build an AI service that survives production
- Build an NLP system end to end
- An AI service in operation
- AI in production
- Training neural networks for real
- Train your first neural network
- Run models more cheaply: quantisation
- Fine-tune and run your own models
- Build a RAG system you can trust