Card 18: Validation
Module 7: Expert Techniques
1 The Hook
Imagine a nightclub without a bouncer. Anyone (or anything) enters.
Validation is the Bouncer. It stops bad data (like Age: -50) from crashing your app.
We use a while loop to keep asking
UNTIL it's right.
2 Worked Example
Validating an Age (Must be 0-120).
PREDICT
What happens if you enter "1234"?
while len(pin) < 4:
print("Too short.")
pin = input("Set PIN: ")
print("Saved.")
while choice < 1 or choice> 3:
choice = int(input("Enter option (1-3): "))
Input Required
Interactive Editor
🥉 Name Check
1. Ask for a name.
2. If user presses Enter without typing, len(name) is 0.
3. Add a loop to force them to type a name.
🥈 Infinite Loop
1. We want a positive number (num > 0).
2. If user types -5, the loop starts.
3. BUT... we forgot to ask for input inside the loop. It crashes!
4. Fix the infinite loop.
🥇 Range Validator
1. Ask for a test score.
2. It must be between 0 and 100.
3. Use while to reject anything < 0 OR > 100.
4. Print "Saved" when valid.