Menu

Condition Controlled Iteration (While Loops)

Sentinel Values

A sentinel value is a special value that means “stop”. It is not ordinary data: it is the signal that ends a while loop. The loop condition compares the latest input with the sentinel, so the loop repeats while the input is not equal to it. Choose a sentinel that normal data would not use, such as -1 for a points total, because a value that could be real data would end the loop too early.

In this program, -1 is the sentinel. Points are added to the total while the entered value is not -1. The input is taken once before the loop and again inside it, so the condition can change. Because the condition is tested before every pass, entering -1 first skips the body and the total stays at zero: the sentinel itself is never added.

Flowchart of a while loop with sentinel -1: total_points = 0, input points, test points != -1; Yes adds to the total and inputs again; No outputs total_points and ends.

total_points = 0
points = int(input("Enter points (-1 to finish): "))
while points != -1:
    total_points = total_points + points
    points = int(input("Enter points (-1 to finish): "))
print("Total points: " + str(total_points))

Output when the user types 4, 6, -1:

Enter points (-1 to finish): 4
Enter points (-1 to finish): 6
Enter points (-1 to finish): -1
Total points: 10

Menus that repeat

A menu can use its exit option as the sentinel. The loop condition checks the user’s choice, and selection inside the loop handles each menu option. Choosing the exit option makes the condition false, so the loop ends and the closing message prints once, outside the loop.

Here, Q is the sentinel. Option B books one seat and option C cancels one, but only while a seat is booked, so the number of seats can never drop below zero.

seats_taken = 0
option = ""
while option != "Q":
    print("B Book a seat, C Cancel a seat, Q Quit")
    option = input("Choose an option: ")
    if option == "B":
        seats_taken = seats_taken + 1
    elif option == "C" and seats_taken > 0:
        seats_taken = seats_taken - 1
print("Seats booked: " + str(seats_taken))

Output when the user types B, C, Q:

B Book a seat, C Cancel a seat, Q Quit
Choose an option: B
B Book a seat, C Cancel a seat, Q Quit
Choose an option: C
B Book a seat, C Cancel a seat, Q Quit
Choose an option: Q
Seats booked: 0

Practise this