SLIDE 1
CSZone.co.uk
Click to advance · Arrow keys also work
Edexcel 1CP2 · Topic 6 · 6.4a

Defensive Design &
Input Validation

Anticipating Errors · Range Check · Type Check · Presence Check · try/except

CSZoneEdexcel GCSE Computer Science 1CP2
What is Defensive Design?

Writing Robust Programs

Defensive design means writing code that anticipates how users might misuse or make mistakes with a program, and handles those situations gracefully rather than crashing or producing wrong results.
Assume the user will enter wrong data — always validate input before processing it
Handle edge cases: what if the user enters nothing? A letter instead of a number? A negative number?
Good documentation and meaningful variable names also contribute to defensive design
Input Validation Techniques

Checking What the User Enters

# Range check
age = int(input("Age: "))
while age < 0 or age > 120:
age = int(input("Invalid. Enter age 0-120: "))

# Presence check
name = input("Name: ")
while name == "":
name = input("Name cannot be empty: ")

# Type check — using try/except
try:
num = int(input("Enter integer: "))
except ValueError:
print("That was not an integer!")
Range check: is the value within an acceptable range?
Presence check: has the user actually entered something (not blank)?
Type check: is the value the correct data type?
try / except in Python

Handling Runtime Errors

valid = False
while not valid:
try:
score = int(input("Enter score (0-100): "))
if 0 <= score <= 100:
valid = True
else:
print("Score must be 0-100")
except ValueError:
print("Please enter a whole number")
print("Score accepted:", score)
try: attempts the code; except: runs if an error of the specified type occurs
This pattern combines type checking and range checking — a robust validation loop
Exam Practice

Have a go at this question

Edexcel-style question
Write Python code that asks a user to enter a password of at least 8 characters, and keeps asking until a valid password is entered.
3 marks
password = input("Enter password (min 8 chars): ")
while len(password) < 8:
password = input("Too short. Try again: ")
print("Password accepted")
Key Takeaways

What to Remember

Defensive design: anticipate misuse, validate all input, handle errors gracefully
Range check: value in valid range; Presence check: not empty; Type check: correct type
try/except: catches runtime errors (e.g. ValueError) without crashing the program
Validation loop: while not valid: — keep asking until correct input received