Sentinel Loops

While Loops

Sentinel Loops

In this tutorial, we'll loop until a special stop value appears.

A sentinel loop repeats until a special stop value appears.

The stop value is called the sentinel.

word = ""

while word != "quit":
    word = input("Type a word, or quit: ")
    print(word)

Here, "quit" is the sentinel value.

Why Sentinel Loops Are Useful

Sentinel loops are useful when you do not know how many times the user will enter data.

Example:

total = 0
number = ""

while number != "done":
    number = input("Enter a number, or done: ")
    if number != "done":
        total = total + int(number)

print("Total:", total)

The user controls when the loop stops.

Choosing a Sentinel

Choose a value the user would not normally enter as data:

  • "quit"
  • "done"
  • "stop"
  • "-1" for positive-only numbers

Tell the user what the sentinel is.

Avoid Printing the Sentinel

In the first example, "quit" gets printed too. If you do not want that, check before printing:

word = ""

while word != "quit":
    word = input("Type a word, or quit: ")
    if word != "quit":
        print(word)

Common Mistake

If you convert input before checking the sentinel, you may get an error:

number = int(input("Number or done: "))  # wrong for "done"

Check for "done" before converting.

Practice

Keep asking for names until the user types "done". Print each name as it is entered.