Stop early, or skip one
break leaves the loop the moment you have your answer. continue skips the rest of this pass and moves on to the next.
- Stop a loop with break as soon as the answer is known
- Skip values you don't want with continue
- Use while True with a break when the stop is decided inside the loop
Often you can stop before the end. Looking for the first bad character in a PIN? Once you've found it, the rest doesn't matter. Other times one value should simply be skipped: a blank line in a stream of barcodes.
breakleaves the loop immediately. No more passes run, and the program continues at the first line after the loop.continueends this pass only. The loop goes straight on to the next character, number or test.
Both almost always sit inside an if, because you only want to stop or skip in some cases.
Run each example to see what it prints. Running examples doesn't count toward progress.
ref = "O104839-2" order = "" for ch in ref: if ch == "-": break order = order + ch print("Order:", order)
while True: is a loop whose test can never be false. It looks endless, but a break inside it ends it. Use it when the decision to stop can only be made in the middle of a pass, after reading a line, for example.
scanned = 0 while True: code = input() if code == "done": break if code == "": continue scanned += 1 print("Scanned", code) print("Total scanned:", scanned)
When to use them: break when the answer is known before the end (the first match, a stop word); continue when some values should be ignored and the rest handled normally.
Mistakes to avoid:
continuein awhileloop before the line that moves it along (n += 1). The skipped pass never changesn, so the loop never ends.- Lines after
breakin the same block never run. Do what has to be done before breaking. breakis notcontinue: one stops the whole loop, the other only this pass.
- break leaves the loop at once; the line after the loop runs next.
- continue skips the rest of this pass; in a while loop, make sure the loop still moves on.
- while True with a break stops in the middle of a pass. Next: a loop inside a loop.