Input validation is the process of inspecting data that has been input to a program, to make sure it is valid before it is used in a computation.
Input validation is commonly done with a loop that iterates as long as an
input variable references bad data.
The integrity of a
program’s output is only as good as the integrity of its input. When input is
given to a program, it should be inspected before it is processed. If the input
is invalid, the program should discard it and prompt the user to enter the
correct data. This process is known as input validation.
Notice that the
flowchart in above figure, it reads input in two places: first just before the
loop and then inside the loop.
The first input
operation—just before the loop—is called a priming read, and its purpose
is to get the first input value that will be tested by the validation loop. If
that value is invalid, the loop will perform subsequent input operations.
Example:
# Get a test score.
score =
int(input('Enter a test score: '))
Make sure it is not
less than 0.
while score < 0:
print('ERROR: The score
cannot be negative.')
score =
int(input('Enter the correct score: '))
This code first prompts
the user to enter a test score (this is the priming read), and then the while
loop executes.
If the user entered a
valid test score, this expression will be false, and the loop will not iterate.
If the test score is invalid, the expression will be true, and the loop’s block
of statements will execute. The loop displays an error message and prompts the
user to enter the correct test score. The loop will continue to iterate until
the user enters a valid test score.