Code

Divide and Conquer

Big problems get easy when you split them into small helper functions, each doing one job. Then a bigger function just calls the helpers, like a captain giving orders.

def area(width, height):
    return width * height

def paint_needed(width, height):
    return area(width, height) / 10   # 1 can per 10 m²

Why bother?

  • Each helper is small enough to understand at a glance.
  • You can test each piece on its own.
  • Fix a bug in one place, and every caller gets the fix.

Pip tip: If you find yourself copying the same lines twice, that's a function waiting to be born.

Assignment

Lantern ferries burn 2 oil per km, and oil costs 3 coins per litre.

  1. oil_needed(km) returns the oil for a trip: km * 2.
  2. oil_cost(litres) returns the price of that oil: litres * 3.
  3. trip_cost(km) returns the total cost of a trip. It must call your two helpers, then add a 5-coin bridge toll if the trip is longer than 10 km.