break
Python Keywords
Reference ยท break
โน๏ธ Leaving a Loop Early
Your number-guessing game is the best possible introduction to break: a loop that has to stop the moment something happens, long before it would end by itself. This page covers what break does in for and while loops, how it behaves in nested loops, how it combines with the loop else block, how it differs from return, and the patterns you will use it for: guessing games, searches, menus and retry loops. Every example below was run, and the output shown is the real output.
break leaves the nearest enclosing loop immediately, in Python, Java and JavaScript alike. The differences are around it. Python has no labelled break (outer: for (...) { ... break outer; }), so leaving two loops at once needs a flag or a function. Python loops can have an else block that runs only when no break happened, which Java and JavaScript lack. And Python has no do-while: while True: plus break is the idiom. JavaScript's forEach cannot be broken out of at all, whereas a Python for loop always can.
while True: + break shape is how backend code talks to slow or unreliable services: keep asking an external API for the next page of results, and break when a page comes back empty; or retry a failed call a few times and break on the first success (Example 7). You will see both constantly in FastAPI services that call other services.
๐งฐ The Building Blocks
Eight pieces. The first three are the everyday uses; the rest are the behaviours that catch people out.
while True: never ends by itself, so it always needs a break somewhere inside. Use it when you cannot know in advance how many passes you need.while with a real condition can still have a break for a second, unrelated reason to stop. Whichever happens first ends the loop.break leaves the nearest loop around it, not all of them. Here the inner loop stops at column 2 on every row, but the outer loop carries on.else that runs only when the loop ends without a break. If a break fires, the else is skipped. Read it as “no break”.break the loop variable still holds the value it had, so you can use it straight away. A loop that finishes normally leaves the last item there instead.return also leaves any loop it is in, and sends a value back as well. Use break to leave a loop and carry on in the same block, and return to leave the whole function.break is only legal inside a for or while. An if on its own is not enough, and Python rejects the file before running anything.๐ How It Works, Step by Step
- The loop runs its body normally, pass after pass.
- When Python reaches the
breakline, it stops the loop at once. Nothing after thebreakin that pass runs, and the loop's condition or its remaining items are never looked at again. - If the loop has an
elseblock, it is skipped. - Execution continues with the first line after the loop, at the loop's own indentation.
When to reach for it: whenever the answer is found, or the job is done, before the loop would end by itself: searching, validating input, menus, retry loops, and every while True loop, which has no other way out.
๐งช In Context
The first three examples are the guessing game from class, built three ways. The rest are the patterns break is used for in real programs.
break is the only exit. The counter goes up before the check, so the winning guess is counted too. The hints are what make this a binary search in disguise: each answer halves the range.Two bugs from class are worth remembering here. Wrapping input() in print() prints None, because print() returns nothing. And input() always gives back a string, so comparing it to the integer target is always False: the int() around it is what fixes that.
break is still needed: without it the loop would keep asking for guesses even after a correct one. The found flag records why the loop ended, so the failure message can be printed once, after the loop, and not on every wrong guess.range(1, 6) gives 1, 2, 3, 4, 5: the end value is excluded, so five passes need 6.
else block runs only if the loop used up all five attempts without a break, which is exactly the “not found” case. Same behaviour as Example 2, one variable fewer.D. Without the break the loop would carry on to the end, which wastes time on a long list and, if there were several matches, would report the last one instead of the first.while True. The menu is shown again and again, and choosing option 3 is the only way out. Anything unexpected falls into the final else and the loop simply goes round again.break outer;. Two clean ways round it: a variable that the outer loop checks after the inner loop ends, or moving the loops into a function so that return leaves both at once. The function version is usually the tidier of the two.for over the attempts, a break on success, and an else for failure.๐ Quick Reference
| What you want | Write | Notes |
|---|---|---|
| Leave the nearest loop now | break | Works in for and while. Everything after it in that pass is skipped. |
| Loop that only ends via break | while True: | Python has no do-while: loop forever, test inside, break when satisfied. |
| Run code only if no break happened | for ...: ... else: | Also works on while. The else is skipped when a break fires. |
| Count attempts in a while loop | tries += 1 | Put it before the check if the winning pass should count. |
| Limit a loop to N attempts | for i in range(1, N + 1): | The end of range is excluded, so add 1. |
| Leave two loops at once | return inside a function | Or a flag checked after the inner loop. There is no labelled break. |
| Leave a function from inside a loop | return value | Leaves every loop and sends the value back. |
| Loop variable after a break | still holds its last value | Handy for “which item stopped us?”. |
| break outside any loop | SyntaxError | Raised before the program runs at all. |
break leaves only one loop: in nested loops it ends the innermost loop and the outer one carries on. There is no break outer; as in Java or JavaScript, so use a flag, or move the loops into a function and return (Example 6).The
else after a loop reads backwards: it does not mean “if the loop did not run”. It runs when the loop finished without a break. Java and JavaScript have nothing like it, so say “no break” to yourself when you read one.A
while True with no reachable break never ends: the program just sits there. Press Ctrl+C in the terminal to stop it, then check that something inside the loop can actually trigger the break.Code after the check does not run on the winning pass: if
tries += 1 came after the if guess == target: ... break, the winning guess would never be counted and “You got it in 3 tries” would say 2. Increment before the test.input() returns a string: input() gives back text, so guess == target compares a string with an integer and is always False. Wrap it in int(). And int() crashes with ValueError on something like abc; the continue page shows how to re-ask instead.There is no
do-while: when you need “do this at least once, then check”, write while True: and put an if ...: break where the real condition would go.break is not used with match: in Java and JavaScript break ends each case of a switch. Python's match statement does not fall through, so no break is needed (or allowed) there unless you are inside a loop.