Python: Input Validation
The Bouncer pattern. Protecting your code from bad data.
The Hook
Imagine a nightclub without a bouncer. Anyone—or anything—enters. This is how software crashes.
Validation is the digital bouncer. We use a while loop to keep asking the user for input UNTIL they enter something sensible.
"Age: -50", "Password: [empty]"
Inside range, right length, right type.
The Bouncer Loop
Validating an Age range (Must be 0-120).
Predict Output
What happens if you enter "1234"?
while len(pin) < 4:
print("Too short.")
pin = input("Set PIN: ")
print("Saved.")
Presence Check
"Add a loop to force the user to type a name. If they press enter without typing, len(name) is 0."
Infinite Crash
"We forgot to ask for input INSIDE the loop. It stays infinite. Fix it!"
Score Limiter
Relational Logic Gate
- Ask for a
score. - While the score is OUTSIDE 0-100...
- Print "Invalid" and ask again.
- Print "Success" when accepted.