In this Python tutorial, we will learn how to break a While loop using break statement, with the help of example programs.
Python – While Loop with Break Statement
Python While Loop executes a set of statements in a loop based on a condition. But, in addition to the standard breaking of loop when this while condition evaluates to false, you can also break the while loop using builtin Python break statement.
The break statement stops the nearest enclosing loop immediately. Execution then continues with the first statement after that loop. This is useful when the loop should stop because a condition is met before the normal while condition becomes false.
break statement breaks only the enclosing while loop.
Syntax of break inside a Python while loop
Following is the syntax of while loop with a break statement in it.
#statement(s)
while condition :
#statement(s)
if break_condition :
break
#statement(s)
Usually break statement is written inside while loop to execute based on a condition. Otherwise the loop would break in the first iteration itself. Above syntax shows a Python If statement acting as conditional branching for break statement.
The statements after break in the current iteration are skipped when the break condition is true. Python exits the loop immediately instead of checking the while condition again.
Following is the flow-diagram of while loop with break statement.
When the break condition is true, break statement executes and comes out of the loop.
Also, please note that the placement of break statement inside while loop is upto you. You can have statements before and after the break statement.
How break changes Python while loop execution
A normal while loop stops when its condition evaluates to False. A break statement provides a second way to stop it: a condition inside the loop can cause an immediate exit even while the main while condition is still True.
- Python checks the
whilecondition. - If the condition is true, the loop body starts executing.
- Python evaluates the condition that controls
break. - If that condition is true,
breakexits the loop immediately. - Execution continues with the statement following the
whileloop.
Python while loop break examples
1 Break While Loop
In this example, we shall write a Python program with while loop to print numbers from 1 to 100. But, when we shall break the loop, after the number 7 is printed to the console.
Python Program
i = 1
while i <= 100 :
print(i)
if i == 7 :
break
i += 1
Output
1
2
3
4
5
6
7
When i reaches 7, the condition i == 7 becomes true and break exits the loop. The statement i += 1 is not executed for that iteration because it appears after the break statement.
2 Breaking Infinite While Loop
In this example, we shall write a Python program with an infinite while loop to print all natural numbers. But, when we shall break the loop, after some eight iterations.
Python Program
i = 1
while True :
print(i)
if i == 8 :
break
i += 1
Output
1
2
3
4
5
6
7
8
Please note that, if we do not write the break statement with the help of Python IF statement, the while loop is going to run forever until there is any interruption to the execution of the program.
while True is commonly used when the loop should continue until an event inside the loop determines that it is time to stop. In such a loop, the exit condition is typically checked with an if statement followed by break.
3 Breaking Nested While Loop
In this example, we shall write a Python program with an nested while loop. We will break the inner while loop based on some condition.
Python Program
i = 1
while i < 6 :
j = 1
while j < 8 :
print(i, end=" ")
if j == 3 :
break
j += 1
print()
i += 1
Output
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
The nested while loop, without break statement would print numbers one to five, eight times each. But because of the break statement, each number is only printed thrice, instead of eight times.
The important point is that this break exits only the inner while j < 8 loop. The outer loop continues and increments i, so the same process runs for values 1 through 5.
Break a Python while loop when a matching value is found
A common use of break is stopping a search as soon as the required value is found. Continuing to inspect the remaining values is unnecessary once the result is known.
numbers = [12, 25, 37, 48, 59]
target = 37
i = 0
while i < len(numbers):
if numbers[i] == target:
print("Found at index", i)
break
i += 1
Output
Found at index 2
When the value 37 is found, break terminates the loop immediately. Values after index 2 are not checked.
Break a Python while loop based on user input
Another common pattern is to keep accepting input until the user enters a particular sentinel value. The loop can use while True and a break condition to stop.
while True:
text = input("Enter text, or type quit to stop: ")
if text == "quit":
break
print("You entered:", text)
print("Loop stopped")
If the user enters quit, Python executes break and skips the remaining statements in the loop body for that iteration. Execution then continues with print("Loop stopped").
Python while loop else behavior when break executes
Python allows an else block after a while loop. The else block runs when the loop ends normally because its condition becomes false. It does not run when the loop is terminated by break.
i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
else:
print("Loop completed normally")
print("After loop")
Output
1
2
After loop
Because break is executed when i is 3, the else block is skipped.
Difference between break and continue in a Python while loop
break and continue both change the normal flow of a loop, but they do different things. break terminates the loop completely. continue skips the remainder of only the current iteration and starts the next iteration if the loop condition still permits it.
| Statement | Effect in a while loop |
|---|---|
break | Stops the nearest enclosing loop immediately. |
continue | Skips the remaining statements in the current iteration and proceeds with the next iteration. |
When using continue in a while loop, make sure the loop-control variable is updated correctly. Otherwise, the loop can repeatedly evaluate the same condition and never terminate.
Stopping nested while loops with break
A break statement affects only the nearest loop containing it. If you have two nested while loops and need to stop both, a single break in the inner loop is not enough. The outer loop needs its own stopping condition or another control mechanism.
stop = False
i = 1
while i <= 3 and not stop:
j = 1
while j <= 3:
if i == 2 and j == 2:
stop = True
break
print(i, j)
j += 1
i += 1
Output
1 1
1 2
1 3
2 1
The inner break exits the inner loop. The variable stop also makes the outer loop condition false, so both loops terminate.
Common mistakes when breaking a Python while loop
- Placing
breakoutside a loop:breakmust appear inside afororwhileloop. - Using an unconditional break unintentionally: a
breakthat always executes during the first iteration makes the loop run only once. - Expecting one break to exit every nested loop: it exits only the nearest enclosing loop.
- Putting required statements after break: statements after an executed
breakin the same loop iteration are not reached. - Using
while Truewithout a reliable exit path: make sure at least one reachable condition can executebreakwhen the loop is expected to terminate.
When to use break in a Python while loop
Use break when the normal loop condition does not fully describe when the loop should stop. Typical cases include stopping after a matching item is found, ending an input loop after a sentinel value is entered, terminating a retry process after success, or exiting an intentionally indefinite while True loop when a specific condition occurs.
If the stopping condition can be expressed clearly in the while condition itself, doing so may make the loop easier to read. Use break when an exit condition naturally occurs inside the loop body or depends on information calculated during an iteration.
Python while loop break key points
breakterminates the nearest enclosingwhileloop immediately.- The
whilecondition does not need to become false forbreakto stop the loop. - Statements after an executed
breakin the current loop body are skipped. breakis often combined with anifstatement that defines the early-exit condition.while Truecan be combined withbreakwhen the stopping condition is checked inside the loop.- In nested loops,
breakexits only the loop in which it appears. - A
whileloop’selseblock is skipped when the loop ends because ofbreak.
Conclusion
In this Python Tutorial, we learned how to break Python While Loop using break statement.
TutorialKart.com