Defensive design is the practice of writing programs that anticipate and handle errors, unexpected inputs, and misuse. A defensively designed program does not crash or behave unpredictably — it guides users and handles problems gracefully.
Key aspects of defensive design include:
Input validation — checking that user input meets expected criteria before using it
Authentication — ensuring the user is who they claim to be
Error handling — using try/except to catch and manage runtime errors
Anticipating misuse — considering how users could accidentally or deliberately break the program
Input Validation
Input validation checks that data entered by a user meets the expected format, type, and range before processing it. Invalid data should be rejected with a clear message, and the user prompted to try again.
Validation type
What it checks
Example
Range check
Is the value within acceptable limits?
Age must be 0–120
Type check
Is the data the correct type?
Must be an integer
Length check
Is the data the right length?
Password 8–16 chars
Presence check
Has data been entered at all?
Name cannot be empty
Format check
Does it match expected format/pattern?
Email must contain @
Validation with a while loop
# Range check — keep asking until validage = int(input("Enter your age: "))while age < 0or age > 120:print("Invalid age. Must be 0-120.") age = int(input("Enter your age: "))print("Age accepted:", age)# Presence checkname = input("Enter your name: ")while name == "":print("Name cannot be empty.") name = input("Enter your name: ")
Error Handling with try/except
Some errors can only be detected at runtime (e.g., trying to convert "hello" to an integer). Python's try/except block catches these without crashing the program.
try: num = int(input("Enter a number: "))print(10 / num)except ValueError:print("Please enter a valid integer.")except ZeroDivisionError:print("Cannot divide by zero!")# Combined: validation with error handlingvalid = Falsewhilenot valid:try: score = int(input("Score (0-100): "))if0 <= score <= 100: valid = Trueelse:print("Must be 0-100.")except ValueError:print("Must be a whole number.")
Authentication
Authentication verifies a user's identity before allowing access. Simple authentication uses a password check:
Exam tip: Defensive design questions are common in Edexcel Paper 2. You may be asked to write validation routines (often using a while loop), add error handling to existing code, or identify what validation checks are missing. Always mention what the program should do if input is invalid — reject it AND re-prompt.
⚠️ Common Mistakes
Only checking one condition — good validation often combines type check + range check + presence check
Letting invalid input crash the program — always use try/except when converting input types
Validation that only checks once (if, not while) — use a while loop to keep prompting
Not giving a helpful error message — tell the user WHAT was wrong and WHAT to enter instead
Forgetting that input() always returns a string — convert before comparing to numbers
✅ Notes completed!
▶
Video coming soon
Click slide or press arrow keys to navigate
✍️
Worksheet — 6.4a Defensive Design
8 Edexcel-style questions · instantly marked
Q1What is defensive design and why is it important in programming?[2]
✅ Mark scheme
Defensive design is a programming approach that anticipates errors, unexpected inputs, and misuse [1]; it is important because it prevents programs from crashing or behaving unpredictably, and ensures data integrity and user experience [1].
Q2Name and describe THREE different types of input validation check.[6]
✅ Mark scheme
Range check: verifies value is within acceptable limits (e.g. 0–100) [2]; Type check: verifies data is the correct type (e.g. integer not string) [2]; Presence check: verifies data has been entered and is not empty [2]. (Accept also: length check, format check — 2 marks each for name + description.)
Q3Write Python code to validate that a user enters a number between 1 and 10 (inclusive). Keep prompting until valid input is given.[4]
✅ Mark scheme
num = int(input("Enter number (1-10): ")) [1]; while num < 1 or num > 10: [1]; print("Must be 1-10") [1]; num = int(input("Enter number (1-10): ")) [1]. Must use while (not if) for repeated validation — if only checks once.
Q4What is a try/except block and when should it be used?[3]
✅ Mark scheme
A try/except block is code that attempts to run instructions in the 'try' section, and catches any errors in the 'except' section [1]; it should be used when runtime errors are possible [1]; for example, when converting user input to an integer — if the user types "hello", int() would raise a ValueError without try/except [1].
Q5A program asks a user for their age. Write code using try/except AND a range check to ensure a valid integer between 0 and 120 is entered.[5]
✅ Mark scheme
valid = False; while not valid: [1]; try: [1]; age = int(input("Enter age: ")) [1]; if 0 <= age <= 120: valid = True; else: print("Must be 0-120") [1]; except ValueError: print("Must be a whole number") [1]. Combines both error handling and range check.
Q6Describe TWO ways in which a simple login system demonstrates defensive design.[4]
✅ Mark scheme
Limiting login attempts (e.g. 3 attempts then lock) — prevents brute force attacks and unauthorized access [2]; Checking that username/password fields are not empty before attempting login — presence check prevents errors [2]. (Also accept: case-insensitive comparison, error messages that don't reveal which field was wrong.)
Q7The following code has a bug — what happens if the user types "abc" and how would you fix it? Code: num = int(input("Enter a number: ")); print(100/num)[3]
✅ Mark scheme
Typing "abc" causes a ValueError because int() cannot convert a non-numeric string [1]; fix by wrapping in try/except: try: num = int(input(...)): print(100/num) except ValueError: print("Not a valid number") [1]; should also handle ZeroDivisionError if user enters 0 [1].
Q8Why is it important to use a while loop (not an if statement) for input validation? What difference does it make?[2]
✅ Mark scheme
An if statement only checks the input once — if invalid, the program continues with invalid data anyway [1]; a while loop keeps re-prompting until valid data is entered, ensuring only valid data is used in the rest of the program [1].
Topic Quiz
Q 1 of 15
You scored
out of 15
Click to reveal definition
🎉
Session complete!
Term
Definition
🎯
Mini Test — Defensive Design
Timed exam-style test — 10 minutes.
⏱10:00
Section A — Multiple Choice [5 marks]
Q1Which validation check ensures a value is within acceptable limits (e.g. 1–100)?[1]
Q2Which error is raised when int("hello") is called?[1]
Q3Why must a while loop (not an if statement) be used for input validation?[1]
Q4What is the purpose of the 'except' block in a try/except statement?[1]
Q5Which check verifies that a field has not been left empty?[1]
Section B — Short Answer
Q6Write Python code to ask for a password and check it against "pass123". Give the user 3 attempts, then print "Locked" if all fail.[3]
Mark schemecorrect = "pass123"; attempts = 0 [1]; while attempts < 3: [1]; pw = input("Password: ") [1]; if pw == correct: print("Access granted"); break [1]; attempts += 1 — else: print("Locked") or equivalent [1].
Q7State TWO types of validation you would apply to a field asking for a student's percentage score (0–100).[2]
Mark schemeType check: ensure the input is a number (integer or float), not a string like "hello" [2]; Range check: ensure the value is between 0 and 100 inclusive [2]. (Accept any 2 of: type, range, presence, length — 2 marks each.)