3.2.11 - Data validation routines (Python)

3.2.11 - Data validation routines (Python)

Validation checks whether input satisfies the program's rules before that input is used. You will write Python length, presence and range checks and repeat a request until its value is permitted.

Checking validity

Validation rejects input that fails a stated rule, reducing the chance that invalid data reaches later processing.

Validation

Checking whether entered data meets specified acceptance rules.

A booking may allow 1 to 10 tickets. Quantity 12 is outside that rule, so it should be rejected before a price is calculated. Quantity 5 passes the range check, but validation cannot prove the user actually intended 5 rather than 6. Valid data is not necessarily accurate data.

Choose the check from the requirement: a compulsory name needs a presence check, a code with a minimum length needs a length check, and a permitted numerical interval needs a range check. These checks test input properties; they do not establish who the user is. Authentication is a separate identity check.

The current AQA guidance allows GCSE exam programs to assume input errors do not concern data type. These numerical examples therefore assume an integer is entered. Conversion with int() supplies the type for arithmetic; implementing type-checking or try/except validation is not an exam prerequisite.

Length, presence and range checks

A validation condition should express the acceptance rule exactly, including its boundaries.

Python
name = input("Name: ")
if name == "":
    print("Name is required")

code = input("Code: ")
if len(code) < 4:
    print("Code is too short")

quantity = int(input("Quantity: "))
if quantity < 1 or quantity > 10:
    print("Quantity is outside the range")

An empty string has length 0. A presence check rejects that empty input; it does not automatically reject a string containing only spaces unless the requirement says to handle that case. The minimum-length rule rejects length 3 but accepts length 4 and above. The range rule rejects a value below 1 or above 10. Its acceptance equivalent is quantity >= 1 and quantity <= 10, where both comparisons must hold.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account