Break Statement in Python
The break
statement in Python is used to stop a loop
immediately, even if the loop condition is still true.
It is mostly used when we want to exit the loop early based on some condition, like finding something in a list or ending a menu program when the user chooses to quit.
Syntax:
for/while loop:
if condition:
break
# remaining loop code
Note: The break
statement is written inside the
loop and usually after an if
condition.
Example 1: Break a loop when a match is found
names = ["Mukesh", "Angel", "Devanshi", "Simran"]
for name in names:
print("Checking:", name)
if name == "Devanshi":
print("Found Devanshi, stopping the loop.")
break
Output:
Checking: Mukesh
Checking: Angel
Checking: Devanshi
Found Devanshi, stopping the loop.
Explanation:
- The
for
loop goes through thenames
list. - For each name, it prints "Checking: name".
- When it finds "Devanshi", the condition becomes true and
break
is executed. - This immediately ends the loop, so "Simran" is never checked.
Example 2: While loop with break
i = 1
while i <= 10:
print(i)
if i == 5:
break
i += 1
Output:
1
2
3
4
5
Explanation:
- The
while
loop starts from 1 and goes up to 10. - Each value of
i
is printed. - When
i == 5
,break
is executed, so the loop stops immediately. - Even though the loop condition allows up to 10, it ends early at 5.
Summary:
- Used to: Exit a loop early when a specific condition is met.
- Works inside: Both
for
andwhile
loops. - Stops loop: Immediately when executed.
- Helpful when: Searching, filtering, or avoiding unnecessary iterations.
Quick Comparison Table:
Feature | break Statement |
---|---|
Use case | Exit loop early |
Can be used in | for and while loops |
When executed | Immediately stops the loop |
After break |
Remaining loop code is skipped |