Lessons 21–25 · About 60 min per lesson

Functions and debugging

Extract reusable rules and isolate bugs with small tests.

Lesson breakdown

  1. Lesson 21

    Define and call a function, identifying parameters and arguments.

  2. Lesson 22

    Return a decision to the caller and let the caller handle the output.

  3. Lesson 23

    Reuse one rule for two barns and distinguish local variables from those in the caller.

  4. Lesson 24

    Test one function with an ordinary approval, equality and a failure.

  5. Lesson 25

    Reproduce a bug with the smallest failing input and compare results before and after the fix.

Worked example

Two barns have 7 and 3 kg respectively and both receive a request for 5 kg. Write the stock rule once.

How to solve it

can_fill(7, 5) is True and can_fill(3, 5) is False. The function decides eligibility, and the caller handles stock updates.

def can_fill(stock, request):
    return stock >= request

Assignment

Write remaining_after_request(stock, request). Return the diminished stock if there is enough, or the original stock otherwise.

Check your result

(7, 5) → 2; (7, 7) → 0; (7, 8) → 7.