Drill

ProblemsPython › validation

Read a quantity someone typed

easyvalidationPython

A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.

valid_quantity(text: string) → int

Solve it in the editor →

Where you start

def valid_quantity(text: str) -> int:
    

Worked examples

CallResult
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

The same problem in another language

More validation problems in Python