Back

Validation and verification using while loops in algorithms and programs

Validation using while loops
A frequently used technique to validate data is to use a while loop. The user has to enter in a value, until either the value is correct or they have used up the amount of goes they are allowed. Here is an example of this.

The user must enter in the correct password. If it is incorrect, they can try again, but they are only allowed three goes before their account is locked and they have to contact the Network Manager.

1    password = "tHe+tr33s"
2    
3    counter = 1
4    guess = input("Please enter password >>> ")
5    
6    while (guess!=password) and (counter<3):
7        guess = input("Please enter password >>> ")
8        counter = counter + 1
9    
10   if guess == password:

11      print("You have entered the correct password. You may continue.")
12   elif counter >= 3:
13      print("Incorrect password. Your account has been locked. Please contact the Network Manager") 
14
15   input("Press <ENTER> to quit >>>>")

You frequently have to enter in a number between two values. You can validate the data entry using a while loop in a similar way to the above. For example:

guess = int(input('Please enter a whole number between 1 and 10 >>> '))

while (guess < 1) or (guess > 10):
    guess = int(input('Please enter a whole number between 1 and 10 >>> '))

print('Thank you. You entered',guess)

Of course, it won't stop your user entering in a decimal. For that, you'd have to add some additional validation. There are a number of ways of doing this. One of them uses our old friend try - except.

while True:
    print('Please enter a whole number between 1 and 10 >>> ')
    try:
        guess = int(input())
    except ValueError:
        continue

    if 1 <= guess <= 10:
        print('Thank you. You entered: ',guess)
    else:
        print('Out of range. Try again')

Try running this code with a range of inputs, including numbers that are out of range, decimals and ones that include letters or symbols. If you are having trouble working out how this code works, use a visualiser. Copy the code into e.g. www.pythontutor.com and then run it one line at a time. You might be able to improve on the above code with a little bit of experimentation!

You could do some research to see how else you might solve the problem of only accepting whole numbers. For example, if you read in a string, could you run a test on the input, to check that it only contains digits?

Back