Key Takeaways — Chapter 6: Functions
What Functions Are
A function is a named, reusable block of code:
def calculate_gross_margin(revenue, cogs):
"""Calculate gross margin as a decimal."""
if revenue == 0:
return 0.0
return (revenue - cogs) / revenue
The DRY Principle
Write business logic once. Put it in a function. Import it everywhere. When the rule changes, update one place — not ten.
Function Anatomy
def function_name(param1, param2, param3=default_value):
"""Docstring: what this function does."""
# Local variables here
result = ...
return result
Key Concepts
| Concept | What It Means |
|---|---|
| Parameters | Names in the function definition |
| Arguments | Values passed when calling |
| Default parameters | def f(x, rate=0.10) — optional inputs |
| Keyword arguments | f(price=100, rate=0.15) — explicit naming |
| Return | What the function sends back |
| Docstring | First string in function body — self-documentation |
| Scope | Local variables exist only inside the function |
| Lambda | One-line anonymous function: lambda x: x * 2 |
| Module | A .py file you can import functions from |
Multiple Return Values
def get_margins(revenue, cogs, expenses):
gm = (revenue - cogs) / revenue
om = (revenue - cogs - expenses) / revenue
return gm, om # Returns a tuple
gross, operating = get_margins(...) # Unpack both
Pure vs. Side-Effect Functions
# Pure: predictable, testable, composable
def calculate_tax(amount, rate):
return amount * rate
# Side effect: changes the world (send email, write file)
def send_invoice_email(client, amount):
# sends email — name clearly signals this
...
Keep them separate. Name side-effect functions with verbs that signal the action: send_, write_, update_, delete_.
Function Design Checklist
- [ ] Does it do ONE thing?
- [ ] Is the name a verb that describes that one thing?
- [ ] Does it have a docstring?
- [ ] Does it validate its inputs (or at least guard against obvious bad inputs)?
- [ ] Is it less than ~20 lines? (If not, consider splitting)
- [ ] Could you test it in isolation?
Next: Chapter 7 — Data Structures: Lists, Tuples, Dictionaries, and Sets.