🎓 A1Learner
🔍

Python Loops With Input

A sentinel loop is a loop that reads lines until one special line appears. That special line is the sentinel.

Read until the stop word

Type milk, then done, each on its own line. Only milk is added before the loop stops.

item = input()
while item != "done":
    print("Added:", item)
    item = input()

Collect each line

Type eggs, then done, each on its own line. Each good line joins the list with +. The stop word itself is never collected.

items = []
item = input()
while item != "done":
    items = items + [item]
    item = input()
print(items)

The match must be exact

Capital letters count in a text match. Done with a capital D is not the sentinel.

word = "Done"
print(word == "done")

Example

items = []
item = input()
while item != "done":
    items = items + [item]
    item = input()

print("Shopping list:")
for item in items:
    print("-", item)
print("Items:", len(items))

Key points

  • Sentinel: a special value that tells a loop to stop
  • A sentinel loop keeps reading lines until the sentinel appears.
  • First read: read one line before the loop, so the condition can test it
  • Read again at the end of each round, so the loop can move on
  • Typed input for the closing example: milk, eggs, bread, done, each on its own line

In this example, you type milk, eggs, bread, then done. Each word goes on its own line. Items starts as an empty list. The first read happens before the loop starts. The loop tests each line against done. Each good line joins items with +. A fresh read at the end gets the next line. When done arrives, the loop stops. The list then prints as lines, with its count.

Note

Pick a sentinel that is not real data.

Here, a line that is exactly done ends the list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does the first input() often sit before a sentinel loop?