Menu

Input

Conversion Is Not Validation

Converting text with int() or float() changes its data type. It does not check that the number makes sense, or that it falls inside an allowed range.

Converting the text 62 with int() works because 62 is a whole number, and a whole number is all the function is asked for. Whether 62 is a reasonable answer is a separate question that the conversion never considers.

bikes_text = input("Number of bikes (1 to 4): ")
bikes = int(bikes_text)
cost = bikes * 12  # cost per bike in pounds
print(cost)

Output when the user types 62:

Number of bikes (1 to 4): 62
744

The prompt asks for 1 to 4 bikes, yet typing 62 still converts without complaint. The program multiplies and prints a price for 62 bikes, because int() only answers whether the text can become a whole number — the answer is yes, so the value is used.

A conversion fails when the text cannot represent the required type — for int(), the word lots cannot become a whole number — and then the program stops with an error. Even that is a judgement about the type, not about whether the value is sensible.

Question askedConversionValidation
Can this text become a number?Checks itDoes not check it
Is the number in the allowed range?Ignores itChecks it
62 typed where only 1 to 4 is allowedAcceptedRejected

So a value can be converted perfectly and still be nonsense. Checking input against rules, such as a range check, is validation, and that belongs with defensive design.

Practise this