Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 06 / Topic 9 of 10

Putting it together: safe number input

We validate a list of simulated user inputs (no input()), so the program always runs. Two traps to know first:

  • float() also accepts "nan" (not a number) and "inf" (infinity). They are not real amounts. math.isfinite(x) is False for both (import math is taught in Part 7).
  • Money has 2 decimals, so round first, then check. Otherwise "0.001" passes the > 0 check but becomes 0.0 after rounding.
import math                      # import is taught in Part 7

def parse_amount(text):
    """Return a positive amount (2 decimals), or raise ValueError with a friendly message."""
    try:
        value = float(text)
    except ValueError:
        raise ValueError(f"'{text}' is not a number") from None
    if not math.isfinite(value):
        raise ValueError(f"'{text}' is not a real amount")
    value = round(value, 2)      # round first ...
    if value <= 0:               # ... then check
        raise ValueError(f"{text} must be more than 0")
    return value

for typed in ["250", "abc", "-40", "99.5", "", "nan", "0.001"]:
    try:
        print("OK:", parse_amount(typed))
    except ValueError as e:
        print("Error:", e)
OK: 250.0
Error: 'abc' is not a number
Error: -40 must be more than 0
OK: 99.5
Error: '' is not a number
Error: 'nan' is not a real amount
Error: 0.001 must be more than 0

from None hides the original error because our message is already clear. Full program: examples/02_safe_number_input.py.

Done here? The practice set for Part 6 — 7 exercises with solutions — is on the part page.

Search the guide