Functions: write the logic once, reuse it forever
Think of a spreadsheet formula you’ve written once and then copied into fifty other cells — trusting each copy still does the same sum correctly. A function is that formula, given a name, written once, and called from anywhere in your script whenever you need it.
Defining a function
def estimate_fee(hours, rate):
return hours * rate
def starts a function definition; estimate_fee is its name; hours and rate are parameters — placeholders for whatever values get handed in when it’s actually used. return sends the result back out to wherever the function was called.
Calling it
print(estimate_fee(12, 250))
print(estimate_fee(3.5, 400))
Each call runs the same two lines of logic with fresh numbers. Nothing about the function changes between calls — only the values you feed it do. Write the calculation once, trust it every time after.
Giving a parameter a default value
def estimate_fee(hours, rate=250):
return hours * rate
print(estimate_fee(6))
print(estimate_fee(6, 300))
rate=250 means: if nobody specifies a rate, assume 250. You can still override it by passing a second value. This is how you bake in a standard rate without losing the ability to charge a different one when a matter calls for it.
Combining it with a loop
matters = [("Okafor & Sons", 12), ("Meridian Health Trust", 3.5), ("Brightwell Logistics", 20)]
for matter, hours in matters:
fee = estimate_fee(hours)
print(f"{matter}: £{fee:.2f}")
(matter, hours) in the loop unpacks each pair straight into two names in one go. And :.2f inside the f-string formats a number as currency — two decimal places, no matter how the maths came out. Put together with last lesson’s loop, this is a genuinely useful little billing script.
What you just learned
A function packages up logic once so you can trust it everywhere you call it; parameters are the inputs, return is the output, and defaults let you set a sensible assumption without losing flexibility. Combined with a loop, that’s enough to run a calculation across an entire list of matters in a few lines.