
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
- Rewrite
parse_amount(text)in EAFP style: return theint, orNoneifint()can't convert it. - Fix
describe(stock, item)so only truly missing items saymissing; an item with0showsrope: 0.
- Rewrite
parse_amount(text)in EAFP style: return theint, orNoneifint()can't convert it. - Fix
describe(stock, item)so only truly missing items saymissing; an item with0showsrope: 0.
main.py Python sleeping
Press Run to try your code, then Check to test it.