Gulberg Green, Islamabad

Programming Fundamentals · Lesson 08

Debug a small program

Trace a workshop budget, find a logic error, and test the fix.

Debugging starts with an expectation. Choose a small example whose answer you can calculate by hand, run the program, and compare the results. A program can run successfully and still use the wrong rule.

This workshop charges 40 per kit and adds a single delivery fee of 10. For three kits, the expected total is 130. The code below runs, but its output differs from that expectation. Follow the parentheses to find the cause.

A useful check pairs an ordinary case with a boundary. For this exercise, assume orders contain at least one kit. Try a single kit and several kits. A single kit alone will hide the error because both formulas produce 50.

Read the example

Python 3
def order_total(kits):
    return kits * (40 + 10)

print(order_total(3))
Expected output
150

The delivery charge sits inside the parentheses, so the program adds it once for each kit. To charge delivery only once, multiply the kit price by the quantity first and then add 10.

Try it yourself

Fix order_total. Check that one kit costs 50 and three kits cost 130. Add an assert statement for each case so Python can check your expectations.

Show a worked solution
def order_total(kits):
    return kits * 40 + 10

assert order_total(1) == 50
assert order_total(3) == 130
print("Both checks passed.")

Check your understanding

Your lesson quiz

Answer all five questions. Score at least 4 out of 5 (80%) to pass. You can retry as often as you like.

1. What should three kits at 40 plus one delivery fee of 10 cost?
2. Why is kits * (40 + 10) wrong for a single delivery fee?
3. Which case reveals the difference between the two formulas?
4. What is a logic error?
5. What does assert order_total(3) == 130 check?

Quiz progress is saved in this browser. View certificates →

Learn together

Was this lesson helpful?

Comments and reactions are not open yet.

WhatsApp