N5 & Higher – Input Validation (Python)

Input validation is used in both National 5 and at Higher. It consists of 3 parts.

  1. Get the user to enter a value
  2. While the value is wrong
  3.     Get the user to enter a value

The use of the while construct allows the program to repeatedly ask the user to enter valid data.

1
2
3
4
5
6
7
8
9
age=0

#Input Validation
age=int(input('Please enter your age>'))
while age<0 or age>120: # Check that age is between 0 and 120
    print('Please check your age is between 0 and 120')
    age=int(input('Please enter your age>'))
    
print('Welcome')

This can also be used with strings, can you work out how to modify the code so that it would only take a ‘Yes’ ‘No’ answer?

Leave a Reply

Your email address will not be published. Required fields are marked *