Tutorial 18/20 — Defensive Design

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.

Bad Data (Crash Risk):

"Age: -50", "Password: [empty]"

Validated Data:

Inside range, right length, right type.

The Bouncer Loop

Validating an Age range (Must be 0-120).

# Validation Protocol
# 1. Get initial input
age = int(input("Age: "))
# 2. Loop while INVALID
while age < 0 or age > 120:
print("Error: Impossible Age!")
# 3. Ask Again inside loop
age = int(input("Try again: "))
print("Access Granted")
Logic Gate

Predict Output

What happens if you enter "1234"?

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

Presence Check

"Add a loop to force the user to type a name. If they press enter without typing, len(name) is 0."

> presence_detector_standby
Level 50: Silver

Infinite Crash

"We forgot to ask for input INSIDE the loop. It stays infinite. Fix it!"

> loop_safety_active
Level 51: Gold

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