0%

Repeating Work with Loops · practice

Stop a Loop with break

A while True cannot stop by changing its . The previous lesson left one running on purpose, waiting for an exit from inside the body.

That exit is break. When Python reaches it, the current loop ends immediately and execution continues on the first line below the loop.

Stop when the answer is found

Searching is a natural first use. Once you find what you need, there is no reason to keep looking:

Try it

The loop checks three names, not four. When name is "Alan", break skips every remaining item. The final print() still runs because it sits below the loop, not inside it.

Without break, this tiny search would merely do one unnecessary check. In a long , or when each check involves real work, stopping at the answer matters.

Give while True a visible exit

Now the unfinished shape from the previous lesson can become a menu that stays open until the person chooses to leave:

while True:
    command = input("Type help or quit: ").strip().lower()

    if command == "help":
        print("Try one small command at a time.")
    elif command == "quit":
        break
    else:
        print("I do not know that command.")

print("Goodbye")

Read the important path in order:

  1. while True starts another pass.

  2. The program asks for a command.

  3. quit reaches break.

  4. Python leaves the loop and prints Goodbye.

The loop is deliberately open-ended, but its exit is not hidden. You can point at the exact choice that reaches break.

Put the result before break

break leaves immediately, so save anything you still need before it:

Try it

If the appeared below break, Python could never reach it. That is a useful debugging question: “Did I store the answer before I left?”

What does this code print?

for value in [3, 7, 11, 15]:
    if value > 10:
        break
    print(value)

print("end")

A loop searches a list for the first unpaid order. What should it do immediately after storing that order?

Now use break in one focused search. The next lesson adds the different idea of skipping one pass without ending the whole loop.

Task

A sensor recorded a of readings. Search for the first reading of 30 or more.

Write one for over readings that:

  • adds 1 to checked for every reading it examines;

  • when a reading is 30 or more, stores it in first_high and uses break to stop the loop.

Keep the two report lines, which run once after the loop.

Expected output:

Readings checked: 3
First high reading: 30

A reading of exactly 30 counts as 30 or more, so the loop should stop there and never look at 45 or 9. Store the reading before break, because Python leaves the loop immediately.