Problems › Python › validation
Read a quantity someone typed
A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.
- Whitespace around the number is fine and is ignored.
- Only digits are allowed — no sign, no decimal point, no spaces inside.
- The value must be between 1 and 999.
- Anything else gives -1.
valid_quantity(text: string) → int
Where you start
def valid_quantity(text: str) -> int:
Worked examples
| Call | Result |
|---|---|
valid_quantity("5") | 5 |
valid_quantity(" 12 ") | 12 |
valid_quantity("999") | 999 |
valid_quantity("0") | -1 |
Hint
Trim, reject an empty result, then check every remaining character before you convert.
Reference solution in Python
def valid_quantity(text: str) -> int:
t = text.strip()
if not t or not all('0' <= c <= '9' for c in t):
return -1
n = int(t)
return n if 1 <= n <= 999 else -1