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:

  1. Checks are often wrong. isdigit() rejects "-3" and " 7 ", which int accepts, and accepts "²", which int rejects.
  2. The check and the action can disagree. A file can vanish between os.path.exists and open.
  3. 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.