After this lesson you can end a loop early, skip over unwanted items, and tell whether a search succeeded. These small keywords make loops much more flexible.
break: stop now
A loop normally runs until its condition fails or its items run out. break ends it at once, wherever you are in the block:
prices = [40, 25, 600, 15, 30]
for price in prices:
if price > 500:
print("Check this price:", price)
break
print("Price ok:", price)
print("Finished checking")Price ok: 40
Price ok: 25
Check this price: 600
Finished checkingWhen the program reaches 600 it prints the warning, break runs and the loop ends. The remaining prices are never looked at. Execution continues on the line after the loop.
break is also how you leave a loop whose condition is always true:
while True:
item = input("Add item (quit to finish): ")
if item == "quit":
break
print("Added", item)
print("Order complete")Add item (quit to finish): tea
Added tea
Add item (quit to finish): coffee
Added coffee
Add item (quit to finish): quit
Order completecontinue: skip this one
continue abandons the current pass and jumps to the next one. It is useful when some items should be ignored:
marks = [72, -1, 85, -1, 64]
for mark in marks:
if mark < 0:
continue
print("Valid mark:", mark)Valid mark: 72
Valid mark: 85
Valid mark: 64Here -1 stands for a student who was absent, so those entries are skipped. Using continue keeps the main work unindented, and the exceptions are handled at the top.
break and continue only affect the nearest loop
If you place a loop inside another loop, break and continue apply only to the loop they are written in, which is the innermost one. The nested loops lesson shows this in action.
The loop else clause
Python has an unusual feature: a loop can have an else block. It runs when the loop finishes normally, meaning it was not ended by break:
for number in [3, 5, 7]:
if number % 2 == 0:
print("Found an even number:", number)
break
else:
print("No even numbers")No even numbersNothing hit break, so the else ran. Now the same code with a list that contains an even number:
for number in [3, 6, 7]:
if number % 2 == 0:
print("Found an even number:", number)
break
else:
print("No even numbers")Found an even number: 6This time break ran, so the else block was skipped. The pattern reads as "search for something; if the loop ended without finding it, do this". It works with while loops too.
Many people find the name confusing. A helpful way to read it is "else, meaning if no break". If you find it hard to remember, you can get the same result with a variable, such as found = False, that you set to True before the break and test after the loop. Both are fine.
pass: an empty block
Sometimes you must write a block but have nothing to put in it yet. A block cannot be empty, so use pass, which does nothing:
for item in ["a", "b"]:
pass
print("Loop done")Loop doneYou will see pass as a placeholder while you sketch a program. Do not confuse it with continue: pass does nothing and the rest of the block still runs, while continue skips the rest of the block.
Choosing between them
- Use break when the job is done and further passes are pointless.
- Use continue when this item is unsuitable but others may be fine.
- Use else on a loop to react to a search that found nothing.
Keeping loops readable
These keywords are tools, not decorations. Used well, continue removes a layer of indentation: instead of wrapping the main work in an if, you reject unsuitable items first and let the rest of the block read straight down. Used badly, several break and continue lines scattered through a long loop make it hard to see when the loop ends.
A good test is to read your loop aloud. If you can say "for each order, skip the cancelled ones, and stop at the first one that is missing a name", the structure is clear. If you need a paragraph to explain it, consider splitting the work into smaller steps or giving the pieces names.
Also remember that a loop can end for two reasons, and your code after the loop may need to know which one happened. The loop else clause is one way to tell.
Common mistakes
- Using break when you meant continue.
breakends the whole loop. If you wanted to skip one item, you needcontinue. - Putting statements after continue. Anything after
continuein the same pass is never reached. - Expecting else to run when the loop is skipped by break. It does not.
- Reading the loop else like an if else. It is not testing a condition. It reports that the loop completed.
- Using break outside a loop. Python rejects it:
breakSyntaxError: 'break' outside loopExercise
A library has the books ["Atlas", "Poems", "Cooking", "Maths"]. Write a loop that looks for the title "Cooking". If found, print its position counting from 1 and stop looking. If it is not found, print that it is not in the library. Use the loop else clause.
Show one possible answer
books = ["Atlas", "Poems", "Cooking", "Maths"]
wanted = "Cooking"
for position, title in enumerate(books, start=1):
if title == wanted:
print(wanted, "is book number", position)
break
else:
print(wanted, "is not in the library")Cooking is book number 3Try changing wanted to "History" to watch the else block run instead.
Next: loops inside loops with nested loops.
Key points
- break leaves the nearest loop immediately.
- continue skips the rest of the current pass and moves on to the next one.
- A loop's else block runs only if the loop finished normally, without hitting break.
- pass does nothing and is a placeholder for a block that must exist but is empty.