Condition Controlled Iteration (While Loops)
A validation loop uses a while loop to keep asking until the user enters acceptable data. The loop repeats while the data is invalid, so the program does not continue with bad input.
Take the first input before the loop so the condition has a value to test.
players = int(input("How many players (2 to 6)? "))
while players < 2 or players > 6:
print("That number is not allowed.")
players = int(input("How many players (2 to 6)? "))
print("Starting a game for " + str(players) + " players.")Output when the user types 1, 9, 4:
How many players (2 to 6)? 1
That number is not allowed.
How many players (2 to 6)? 9
That number is not allowed.
How many players (2 to 6)? 4
Starting a game for 4 players.
The condition in the example checks for values outside the allowed range: players < 2 or players > 6. It is written as invalid rather than valid because a while loop repeats while its condition is true. When the input is invalid, the error message and a new input are placed inside the loop. The new value is stored in the same variable, so the condition can change the next time it is checked. If the first value is already valid, the condition is false straight away and the loop body is skipped.
The condition is checked again at the start of every iteration, so invalid entries can be corrected one at a time. Once the value is valid, the loop ends and the program continues after it. Taking a new input inside the loop is essential; without it the same invalid value would be tested again and again.
Edexcel GCSE Computer Science · Condition Controlled Iteration (While Loops)
Edexcel GCSE Computer Science · Arrays (Lists)
Edexcel GCSE Computer Science · Input Validation