Understanding the Python break Statement: Usage and Examples
Table of Content:
With the break statement we can stop the loop before it has looped through all the items. Jump Statements Python offers two jump statements-break and continue to be used within loops to jump out of loop iterations.
- break statement It terminates the loop it lies within. It skips the rest of the loop and jumps over to the statement following the loop.
- continue statement Unlike break statement, the continue statement forces the next iteration of the loop to take place, skipping any code in between.
Loop with break condition at the top
This is a normal while loop without break statements. The condition of the while loop is at the top and the loop terminates when this condition is False
.
Flowchart of Loop With break Condition at Top
# Break in top name = ["atnyla", "python", "code"] for x in name: if x == "python": break print(x) print("Body after break")
Output
atnyla Body after break
Loop with break condition in the middle
This kind of loop can be implemented using an infinite loop along with a conditional break in between the body of the loop.
Flowchart of Loop with Condition in Middle
Exit the loop when x is "python":
Code
# Break in middle name = ["atnyla", "python", "code"] for x in name: print("Body before break") if x == "python": break print(x) print("Body after break")
Output:
Body before break atnyla Body after break Body before break
Loop with break condition at the bottom
This kind of loop ensures that the body of the loop is executed at least once. It can be implemented using an infinite loop along with a conditional break at the end. This is similar to the do...while loop in C.
Flowchart of Loop with break Condition at Bottom
# Break in Bottom name = ["atnyla", "python", "code"] for x in name: print(x) print("Body before break") if x == "python": break
Output
atnyla Body before break python Body before break