Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Defensive Design

Validation subprograms

All topicsPractise exam questions
Knowledge organiser

Defensive Design

301.16d

Reusable validation routines.

What you need to know

Writing validation as a function makes it reusable. A validation function takes input, checks it, and either returns the valid value or keeps asking until it's correct.

Key points

  • Put validation logic in a function for reuse
  • Function can loop until valid input is received
  • Return the validated value to the caller
  • Can be called from anywhere in the program

Code examples

Validation function
python
def get_int_in_range(prompt, low, high):
    value = int(input(prompt))
    while value < low or value > high:
        print("Must be " + str(low) + "-" + str(high))
        value = int(input(prompt))
    return value

age = get_int_in_range("Age: ", 0, 120)