Python For GCSE
Validation is checking that user or file input data is 'reasonable'. We cannot check that the user is entering correct data. We can, however, ensure that it seems to be correct.
When a user is entering data at the prompt, they may make typographical errors or not understand what is expected to be entered. You may have made your own programs crash by accidentally doing this or by pressing enter before you managed to enter something. Validation is a set of techniques we use to prevent the crashes and logic errors caused by 'unreasonable' input.
Some validation checks we can perform are,
- presence check - checking that something has been entered.
- type check - checking that the correct type of data have been entered.
- range check - checking that a number or date is not outside the range of acceptable values.
- length check - checking that a string has no more or no fewer characters than expecteed.
- lookup check - checking that a value is one of a list of accepted values.
- uniqueness check - checking that a value is unique.
- format check - checking that a string follows an expected pattern.
Another example of a validation check is a check digit like you would find on EAN 13 barcodes. The algorithm for this is one of the tasks in the section on lists.
Task 1 - Presence Check
Here is the code for a presence check. Test the code and write in any comments that help you to understand how it works.
# presence check - inp must be a string def presence_check(inp): if len(inp)>0: return True else: return False # testing the presence check print("Presence Check") print("**************") pres = False while not pres: p = input("You must enter something: ") pres = presence_check(p) print("Passed the presence check.", p) print()
The code used here is going to be useful for writing and testing the other validation functions on this page.
Task 2 - Type Check Integers
The function below checks to see if the input is an integer. It uses a technique called exception handling. An exception is an error that would cause a program to crash. The try structure allows you to see if a statement would crash and handle that scenario without causing the program to end.
# type check integer - inp is a string def is_integer(inp): try: x = int(inp) except: return False else: return True
Add the code that is needed to test this function. Look back at the code from Task 1 to help you. Your program should have the user input data until they enter an integer.
Task 3 – Type Check – Adapt For Floats
Copy the code that you wrote for Task 2 and rewrite it so that the user must enter a float. Test the program. Does the program that requires a float allow the user to enter an integer value?
Task 4 – Range & Type Check
When we do a range check, it is worth our while to also check that we have the correct type. Copy and test the code below. Then adapt to work with ranges of floating point numbers.
# type check integer - inp is a string def is_integer(inp): try: x = int(inp) except: return False else: return True # range check - inp must be a numeric type def range_check(inp,minval,maxval): if inp>=minval and inp<=maxval: return True else: return False # testing the range check print("Range Check") print("***********") r = False while not r: x = input("You must enter an integer from 1 to 10: ") r = is_integer(x) # if it can be converted to an integer... if r: x = int(x) # do the range check r = range_check(x,1,10) print("Passed the range check (1 to 10).", x) print()
Task 5 - Length Check
Here are two functions that check the length of an input. The first makes sure that the length is no larger than a maximum value. The second checks that an input string is of the exact length. Copy the code and add more code to test that these work.
# length check - inp must be a string def length_upto(inp, maxlen): if len(inp)<=maxlen: return True else: return False # length exact - inp must be a string def length_exact(inp,exactlen): if len(inp)==exactlen: return True else: return False
Write a length check function that checks that a string is at least as long as a given value. Adapt the function, length_upto and make yourself a function, length_at_least. Write code to test that function.
Task 7 - Lookup Check
A look-up check is where you check if a value exists in a list of acceptable values. The following function returns true if the input value is a member of the list, alist.
# lookup - check if inp is in alist def lookup(inp, alist): if inp in alist: return True else: return False testlist = ["John", "Paul", "George", "Ringo"]
Using the list, testlist, add code to make it so that the user has to type in the name of a Beatle.
Task 8 - Lookup Too
A lookup check can also be performed when you want to ensure that the input only uses certain characters.
# lookup - check if inp is in astring def lookup(inp, astring): for t in inp: if t not in astring: return False return True alpha = "abcde ,.'ABCDE"
1. Add the necessary code to test this program.
2. Use this idea to validate a person's name. Consider which characters are and are not valid for a name.
3. Copy the function and write an adapted version called excluding(inp, astring). Adapt the code to make sure that the user has to enter a string that does not contain any of the characters that appear in the astring parameter.
Task 9 - Uniqueness
The lookup routines have both been written in a way that allows you to use them to check for uniqueness. Write a short program that keeps asking for input whilst the last input was a unique value.
- Start with an empty list.
- If the user enters something that is not in the list, append that item to the list.
- Keep going until the thing that they enter is in the list, because it was previously entered.
Task 10 - Format Check
Post codes come in the following formats, where 'L' means a letter and 'D' means a digit.
- LLD DLL
- LLDD DLL
- LLDL DLL
- LD DLL
- LDD DLL
- LDL DLL
This is nicely explained on the Wikipedia page on post codes, which also has this table.
The last 3 digits of a post code (inward code) are always a digit followed by two letter characters.
You could use a slice to extract the last three digits from the input string.
To check if this part of a post code is valid, you need to make sure it consists of a digit, followed by two letters.
- Make two strings. One string should consist of the digits 0 to 9, the other of the letters of the alphabet.
- Write a function that checks whether a character appears in a given string (two parameters, the character and the string to look in).
- Write a second function that checks the inward code to make sure it consists of a digit followed by two letters.
Write and test this part of the code first.
The key to validating the post code as a whole, using the code from before, is to split the post code into two parts. The first part is everything up to the space, the second part is those last 3 characters that you previously validated.
There are 6 valid versions of the 'outward code' part of a post code. Combine a check for each of these with your code for the outward code and you will have what it takes to validate a post code. This is quite a complex task and you may benefit from thinking carefully about the logic. It is also worth remembering that, if any character in the post code is invalid, you do not need to test the rest and can simply return false.