When we accept user input we need to check that it is valid. This checks to see that it is the sort of data we were expecting. Verification, by contrast, refers to checking if the data input is correct, not merely valid.
Method 1: Use a flag variable. This will initially be set to False. If we establish that we have the correct input then we set the flag to True. We can now use the flag to determine what we do next (for instance, we might repeat some code, or use the flag in an if statement). Method 2: Use try/except. Here, we try to run a section of code. If it doesn’t work (for instance, we try to convert a string to a number, but it doesn’t contain a number) then we run the except block of code.
Types of validation:
Type check Checking the data type e.g. int, float etc. Length check Checking the length of a string
Range check Checking if a number entered is between two numbers
age = int(input('How old are you? '))
print('Please enter a whole number')
print('Your age is: ' + str(age))
Note: This example isn’t easy to understand if it is new to you, but it is the easiest way to ask the user to enter an input and check the input contains an integer.
Using a flag
flagName = False
while not flagName:
if [Do check here]:
flagName = True
Using an exception
[run code that might fail here]
print('This is the error message if the code fails')