EAFP vs LBYL
There are two styles for code that might fail.
- LBYL, "look before you leap": check first, then act.
if text.isdigit(): int(text). - EAFP, "easier to ask forgiveness than permission": just do it, and
catch the failure.
try: int(text) except ValueError: ...
Python leans towards EAFP, for three reasons:
- Checks are often wrong.
isdigit()rejects"-3"and" 7 ", whichintaccepts, and accepts"²", whichintrejects. - The check and the action can disagree. A file can vanish between
os.path.existsandopen. - Doing the work once is faster than checking and then doing it.
When a missing value is normal, not an error, the simplest tool wins:
stock.get("cake", 0).
Interviewers ask "what does Pythonic mean?". This is a good example.
Run it, then add "1_000" to the inputs.