Sub topic 5
Leaving a loop early with break
This chapter assumes you can write a basic while loop, use comparison and boolean operators, write if statements with correct indentation, and call print and input. It also assumes you know that a loop needs a state change to end, and that while True runs until something stops it.
What break does
A while loop normally ends when its condition becomes false. The check happens only at the top of each pass. If something in the middle of the body tells you to stop, the loop would otherwise finish that pass first.
The break statement ends the nearest enclosing loop immediately. Python skips the rest of the body, skips the condition check, and continues with the first statement after the loop.
break is almost always inside an if. Without a test around it, the loop would stop on its first pass.
while True with break
Some loops have no natural condition up front. You want to repeat until an event happens, such as correct input or a finished download. Here while True is the usual pattern, with break as the exit.
attempts = 0
while True:
answer = input("Password: ")
attempts += 1
if answer == "secret" or attempts == 3:
break
print("Done after", attempts, "attempt(s)")The loop has two ways to stop: the right password or the third try. Both are tested in one place. If you wrote this with a normal condition, you would have to set up a variable before the loop and repeat the input call to get a first value.
You can also have several break statements in one loop, one for each reason to stop.
Breaking out of a search
Searching is the other common use. Once you find what you want, there is no reason to keep looking.
names = ["Ana", "Ben", "Cleo", "Dev"]
target = "Cleo"
i = 0
found = False
while i < len(names):
if names[i] == target:
found = True
break
i += 1
if found:
print(f"{target} is at index {i}")
else:
print(f"{target} not found")This prints Cleo is at index 2. Notice two details:
i += 1comes after theif. Whenbreakruns,istill holds the index of the match. The loop variable keeps its value after the loop ends, so you can use it afterward.- The
foundflag records why the loop stopped. After the loop, you can't tell fromialone whether the loop ran out of items or hit a break. A later chapter shows how the loop'selseclause can replace this flag.
break and your update step
break leaves the loop, so any state update placed after it in the body does not run on that pass. That is usually what you want. It becomes a problem only if code after the loop expects the update to have happened.
Compare the search above with a version that moves i += 1 to the top of the body. The index would then be one too high when break runs. When you use the loop variable after the loop, check where the update sits relative to the break.
Common mistakes
The mistakes below come up often with break.
- Using break outside a loop. Python raises
SyntaxError: 'break' outside loop. Abreakinside anifthat is not inside any loop will cause this. - Forgetting that break needs a condition. An unconditional
breakat the top level of a loop body makes the loop run at most once. - A
while Truewith no reachable break. If the test that triggersbreakcan never become true, the loop never ends. For example,if attempts == 3fails to trigger ifattemptsis never incremented. Check that every path through the body moves toward abreak. - Expecting break to leave several loops. In nested loops,
breakends only the innermost one. Nested loops get their own chapter. - Putting cleanup inside the loop after break. Code after
breakin the same block never runs. Put cleanup after the loop.
Summary
break ends the nearest loop at once and resumes after it. Pair it with if inside while True for event-driven loops, and use it in searches to stop at the first match. Check where your updates sit, and make sure some path always reaches a break.
Exercise
This loop should stop at the first number divisible by 7, then print it. What does it print, and why? n = 20 while n < 100: n += 1 if n % 7 == 0: break print(n)
Show answer
It prints 21. The loop starts at 20, and n becomes 21 on the first pass. Since 21 % 7 is 0, break runs and the loop ends with n still equal to 21. The condition n < 100 is never checked again.
Exercise
Rewrite the password example so it prints "Access granted" only when the user gave the right password, and "Locked out" otherwise. What extra piece of state do you need?
Show answer
You need a way to record why the loop stopped, such as a boolean flag. Set granted = False before the loop. Inside it, when answer == "secret", set granted = True and break. Also break when attempts == 3. After the loop, print "Access granted" if granted is true, and "Locked out" otherwise.