Bug hunt

Pythonic Polish

Two styles of being careful:

  • LBYL, "Look Before You Leap": check first, then act. if text.isdigit(): n = int(text)
  • EAFP, "Easier to Ask Forgiveness than Permission": just try it, and handle the failure.
try:
    n = int(text)
except ValueError:
    n = None

Python code usually prefers EAFP. The check and the action can't disagree. It also handles cases your check forgot, like "-3" or " 7 ": int() accepts them, but isdigit() rejects them.

Truthiness is another idiom: write if items: instead of if len(items) > 0:. But watch out: 0, "" and [] are all falsy. When 0 is a real value and you're checking for "missing", test is None explicitly.

(And the third idiom you already know: with open(...) as f: closes files for you, even when errors happen.)

The bug

The supply clerk reports that "-3" and " 7 " are rejected as non-numbers, and an item with 0 in stock is reported as missing.

Assignment

  1. Rewrite parse_amount(text) in EAFP style: return the int, or None if int() can't convert it.
  2. Fix describe(stock, item) so only truly missing items say missing; an item with 0 shows rope: 0.