🐍 Paper 2 · Topic 6: Programming
6.4a Defensive Design & Input Validation
Edexcel 1CP2 · GCSE Computer Science · ~12 min read · 🆓 Free
Notes
──
Video
──
Slides
──
Worksheet
──
Quiz

What is Defensive Design?

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 typeWhat it checksExample
Range checkIs the value within acceptable limits?Age must be 0–120
Type checkIs the data the correct type?Must be an integer
Length checkIs the data the right length?Password 8–16 chars
Presence checkHas data been entered at all?Name cannot be empty
Format checkDoes it match expected format/pattern?Email must contain @

Validation with a while loop

# Range check — keep asking until valid age = int(input("Enter your age: ")) while age < 0 or age > 120: print("Invalid age. Must be 0-120.") age = int(input("Enter your age: ")) print("Age accepted:", age) # Presence check name = 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 handling valid = False while not valid: try: score = int(input("Score (0-100): ")) if 0 <= score <= 100: valid = True else: 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:

correct_password = "secure123" attempts = 0 while attempts < 3: pw = input("Enter password: ") if pw == correct_password: print("Access granted!") break attempts += 1 print("Wrong password.", 3 - attempts, "attempts left.") else: print("Account locked.")
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
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!
TermDefinition
🎯

Mini Test — Defensive Design

Timed exam-style test — 10 minutes.

← 6.3c File HandlingTopic 6 · PythonNext: 6.4b Testing →