Menu

Condition-Controlled Iteration

Stopping values

A stopping value (also called a sentinel value) is a special input that ends a while loop. Instead of repeating a fixed number of times, the loop keeps going until the latest input matches that value. That only works if you compare the latest input with the stopping value in the loop condition, and take the input inside the loop so there is a new value on each pass.

For example, a school equipment desk logs borrowers until the librarian types -1. If the loop condition is while borrower != -1:, the exact value -1 makes the condition false, so the loop ends and -1 is not counted as a borrower. Written as a stopping condition, the test is borrower == -1, which becomes true exactly at the sentinel.

Combining a counter with a stopping value

A loop can also have a counter so it does not run too many times. Put the counter test and the stopping-value test in the same condition with and when both must still be true to carry on. The loop then ends when either the limit is reached or the stopping value is entered.

total = 0
count = 0
number = int(input("Enter a number, or 0 to finish: "))
while number != 0 and count < 4:  # stop on 0 or after four numbers
    total = total + number
    count = count + 1
    if count < 4:
        number = int(input("Enter a number, or 0 to finish: "))
print("Numbers added:", count)
print("Total:", total)

Output when the user types 6, 4, 0:

Enter a number, or 0 to finish: 6
Enter a number, or 0 to finish: 4
Enter a number, or 0 to finish: 0
Numbers added: 2
Total: 10

Choosing the comparison

The condition is the carry-on condition: it says what must be true for another pass, the opposite of the stopping condition. If the loop should stop the moment a value equals the sentinel, use != in the carry-on test so that exact value ends it. For a limit, use < if reaching the limit must stop the loop, or <= if the limit value must still be processed.

JobCarry-on conditionWhat ends the loop
Stop on sentinel 0while number != 0:0 is entered
Stop when score reaches 10while score < 10:score becomes 10
Process up to and including 10while score <= 10:score goes above 10

Use or only when the loop should carry on if either condition is true; it then ends when both are false. For example, a game could carry on while time remains or lives remain, stopping only when both are gone.

Practise this