Python Control Statements
Python Break Statement
Learn Python Break Statement with clear explanations, Python examples, and practical programming guidance.
What is the Python break statement?
The break statement stops the nearest loop immediately. After Python executes break, control moves to the first statement after that loop. It is useful when the result has been found or continuing would be unnecessary.
Syntax of break
for item in sequence:
if condition:
break
# code that runs until the condition is metIn nested loops, break exits only the innermost loop where it appears.
Stop a for loop
This loop stops when the number reaches 6, so 6 and the remaining values are not printed:
for number in range(1, 11):
if number == 6:
break
print(number)Output
2
3
4
5
Find an item in a list
break prevents unnecessary work after the requested item is found:
fruits = ["apple", "mango", "banana", "orange", "kiwi"]
for index, fruit in enumerate(fruits):
if fruit == "kiwi":
print("Fruit found!")
print("Located at index =", index)
breakOutput
Located at index = 4
Use break in a while loop
A while True loop can be stopped safely when a condition inside the loop becomes true:
count = 1
while True:
print("Count:", count)
if count == 5:
print("Condition met! Exiting loop.")
break
count += 1Output
Count: 2
Count: 3
Count: 4
Count: 5
Condition met! Exiting loop.
Break from nested loops
A break statement exits only the inner loop. A flag can be used to exit the outer loop after the value is found:
matrix = [
[10, 15, 20],
[25, 30, 35],
[40, 45, 50]
]
target = 30
found = False
for row in matrix:
for number in row:
if number == target:
print("Number found:", target)
found = True
break
if found:
breakOutput
For more complex searches, placing the loops inside a function and returning when the item is found can be clearer than using a flag.
break versus continue
| Statement | What it does | Result |
|---|---|---|
break | Stops the nearest loop. | No later iterations run. |
continue | Skips the current iteration. | The loop continues with the next item. |
pass | Does nothing. | The loop continues normally. |
Common mistakes
- Remember that
breakexits only the nearest loop. - Do not use
breakwhen you only need to skip one item; usecontinueinstead. - When using
while True, make sure a reachable condition eventually executesbreak. - Keep the stopping condition clear so readers understand why the loop ends.
Further Reading
Continue learning with these related Python tutorials:
Continue learning
