A system is used to enter 5 valid student ages from 14-18 inclusive:
Can you see what is happening?
Code has been written to check the data entry. The code asks are you valid? and if the input is not valid an error message appears and the user has to try again.
These methods of checking valid or invalid data entry are known as validation checks.
When a user enters data into a computer program, it often needs to be checked. The question is is the data valid? This means, does the data suit the scenario.
Here is some sample Python code which asks a user to enter a number between 1 and 10. Using a while loop, the user is trapped in a loop until (s)he enters a valid number:
Notice how it works:
| check | description | |
|---|---|---|
| length check | to check that the length of the input string is valid. | |
| presence check | to check that there is any data present when input. | |
| format check | to check that the data is in the correct format eg 12:34:00 for time data, not 12;34;00 which is invalid. | |
| range check | to check that numerical data, eg somebody's age, is within a certain range eg 13-19 for a teenager. | |
| type check | to check that the data type is correct, eg we cannot enter hello (a string) when we should enter someone's age (an integer). |
But what if we want to enter more than 1 valid number? For example, we want to use a COUNT CONTROLLED LOOP to process 5 numbers?
A FOR loop can be used to get 5 valid numbers.
A while loop can be used to validate each number entered by the user.
Let's consider it from a PSEUDOCODE perspective:
total ← 0
FOR i ← 1 TO 5
OUTPUT i+1,": enter a number between 1 and 10 inclusive: "
INPUT number
WHILE number < 1 OR number > 10 DO
OUTPUT "Invalid data! Try again."
INPUT number
END WHILE
total ← total + number
END FOR
OUTPUT "The total age is ", total
Code the above algorithm in Python. Can you get it working? Test it using the following test data:
| 0 | -1 | 5 | 7 | 9 | 14 | 18 | 3 | 5 |
You should get an answer of 29.
A computer program asks users to enter a valid season. A valid season is any one of spring, summer, autumn or winter
.Once a valid season has been entered, a seasonal message is displayed on the screen.
This process continues indefintely.
Don't jump to coding immediately.
Take the BIG problem and decompose it into a series of small steps.
Then, solve each step!