Repeating Work with Loops · practice
Stop a Loop with break
A while True
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:
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
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:
while Truestarts another pass.The program asks for a command.
quitreachesbreak.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:
If the 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 30 or more.
Write one for readings that:
adds
1tocheckedfor every reading it examines;when a reading is
30or more, stores it infirst_highand usesbreakto 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.