──────────────────────────────────────

31. Check the Library Shelves · Skip an Item or Stop Searching

Use continue to skip an item and break to stop after finding a result.

Lesson files · lessons/iteration-patterns/skip-or-stop-a-loop

Before you start
- Assign a starting value that can change inside a loop.
- Number items with enumerate().
- Use if to check the value for one item.

By the end
- Use continue to skip one item and break to end a search.
- Trace which shelf keeps its original number after a skip.
- Test a list with no matching shelf.

Where you can use it
Find the first available spot in a row. Skip reserved spots and stop when you reach the first one you can use.

Inside a loop, continue skips the rest of the current trip and lets the loop move on to the next item. break exits the loop immediately. The lines after the loop still run.

In the example, the reader wants the first name with three letters or fewer. A dash stands for a blank space, so continue skips it before the length test. Give the result a default before the loop. When a name matches, replace the result and use break to keep the first match.

For the shelf search, enumerate() gives each status its number as soon as the loop visits it. Skipping a closed shelf leaves the next shelf's original number in place.

Predict
Which name is printed if you remove the break line?
- Ben
- Uma

Worked example (example.py)

names = ["Nandi", "-", "Uma", "Ben"]
chosen = "No match"
for name in names:
    if name == "-":
        continue
    if len(name) <= 3:
        chosen = name
        break
print(chosen)


Example result
Uma

Read one line of shelf statuses separated by spaces. The possible statuses are closed, clear and check. Use continue to skip a closed shelf. Use break when you find the first check. For closed clear check check, print Review shelf 3. If there is no check, print All clear. Keep the original shelf numbers even when you skip a status.

Starter program (starter.py)

statuses = input().split()
message = "All clear"
for number, status in enumerate(statuses, start=1):
    print(f"Shelf {number} - {status}")
print(message)


Starter input
closed clear check check

Hint
Use enumerate(statuses, start=1) and store a default message before the loop. After continue skips closed, status != "clear" detects a shelf to review.

Case 1. Try the sample
Input
closed clear check check
Expected output
Review shelf 3

Case 2. First shelf needs review
Input
check closed clear
Expected output
Review shelf 1

Case 3. No review needed
Input
closed clear closed
Expected output
All clear

Stretch
Write a version that lists every shelf to review. Try the sample input and compare where the two programs stop.

Reflect
Which line lets the search move on from a closed shelf? Which line ends the search?

Check your prediction
Ben The search visits both short names. Ben meets the length rule and replaces Uma as the result.
