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).

# 1. Get initial input
age = int(input("Age: "))
# 2. Loop while INVALID (Less than 0 OR > 120)
while age < 0 or age > 120:
print("Impossible!")
# 3. Ask Again inside loop
age = int(input("Try again: "))
print("Accepted.")

PREDICT

What happens if you enter "1234"?

pin = input("Set PIN: ")
while len(pin) < 4:
  print("Too short.")
  pin = input("Set PIN: ")
print("Saved.")

Interactive Editor

> _
BRONZE (MODIFY)

🥉 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.

> _
SILVER (FIX)

🥈 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.

> _
GOLD (MAKE)

🥇 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.

> _