Python module
Lesson 5
Control flow and functions
if/for/while and small def helpers — the spine of every data script.
beginner35 minRun on your machine
What you will be able to do
- Write if/elif/else and for loops over lists and dicts
- Define functions with arguments and return values
- Keep business logic in small testable helpers
Why this matters for data work
Pipelines are loops over files or rows, with branches for bad data, wrapped in functions you can reuse and test. Giant scripts without def become unmaintainable on day three.
Concepts
if / elif / else — branch on conditions.
for — iterate a sequence: for row in rows:.
while — rarer in data scripts; prefer for when the collection is known.
def — name a block of code. return sends a value back. Prefer pure helpers (same inputs → same outputs) for transforms.
f-strings — f"count={n}" for readable messages.
Practice on your machine
cd ~/dcubes/python-lab
source .venv/bin/activate
cat > functions_lab.py << 'EOF'
def line_total(quantity: int, unit_price: float) -> float:
return quantity * unit_price
def normalize_status(raw: str) -> str:
value = raw.strip().lower()
if value in {"done", "complete", "completed"}:
return "completed"
if value in {"cancel", "cancelled", "canceled"}:
return "cancelled"
return value
orders = [
{"sku": "SKU-1", "quantity": 2, "unit_price": 10.0, "status": "Done"},
{"sku": "SKU-2", "quantity": 1, "unit_price": 5.5, "status": "CANCEL"},
]
for order in orders:
total = line_total(order["quantity"], order["unit_price"])
status = normalize_status(order["status"])
print(f"{order['sku']} total={total} status={status}")
EOF
python functions_lab.py
SKU-1 total=20.0 status=completed
SKU-2 total=5.5 status=cancelled
What you should see
- Two printed lines with computed totals and normalized statuses.
- Type hints on
deflines are optional at runtime — they document intent (more in a later lesson).
Common mistakes
- Mutating global lists inside functions without clear ownership.
- Deep nesting instead of early
continue/ helper calls. - No return — function falls off the end and returns
Noneby accident.