βπ Python Break & Continue β Controlling Loop Flow
Introduction π
break and continue are loop control statements that help you manage how loops execute. They give you more control by allowing you to **stop** the loop early or **skip** certain iterations.
Note
π‘ These statements can be used inside both for and while loops.
1. The break Statement π
break immediately stops the loop and moves control to the first statement after the loop.
break_basic.py
for i in range(1, 10):
if i == 5:
break
print(i)βοΈ The loop stops when i == 5.
βοΈ Values printed: 1, 2, 3, 4.
Break in While Loop
break_while.py
i = 1
while i <= 10:
if i == 7:
break
print(i)
i += 12. The continue Statement π
continue skips the current loop iteration and moves to the next cycle.
continue_basic.py
for i in range(1, 6):
if i == 3:
continue
print(i)βοΈ When i == 3, printing is skipped.
Continue in While Loop
continue_while.py
i = 0
while i < 5:
i += 1
if i == 4:
continue
print(i)3. Break & Continue in Nested Loops πͺ
Break only stops the INNER loop
nested_break.py
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)Note
βοΈ Break affects only the loop in which it is written, not the outer loop.
Continue only skips the inner loop iteration
nested_continue.py
for i in range(3):
for j in range(3):
if j == 1:
continue
print(i, j)4. Using Break in Search Operations π
search_break.py
nums = [10, 20, 30, 40, 50]
search = 30
for n in nums:
if n == search:
print("Found:", n)
break5. Using Continue for Filtering π―
filter_continue.py
for i in range(1, 10):
if i % 2 == 0:
continue
print(i)βοΈ Prints only odd numbers.
6. Real-World Examples π
ATM PIN System
atm_pin.py
attempts = 0
while attempts < 3:
pin = input("Enter PIN: ")
if pin == "1234":
print("Login successful!")
break
else:
print("Wrong PIN")
attempts += 1
else:
print("Account locked!")Skipping Invalid Data
skip_invalid.py
data = ["10", "20", "abc", "30"]
for item in data:
if not item.isdigit():
continue
print(int(item))Note
βοΈ Invalid numeric strings like "abc" are skipped.
7. Important Rules β οΈ
- break exits the loop completely.
- continue skips current iteration and moves to next.
- Both work only inside loops (for/while).
- break inside nested loops affects only the inner loop.
Conclusion π
>>βBreak gives you control to stop. Continue gives you the power to skip. Together they control your loopβs rhythm.β β¨
You now fully understand break and continue in Python! Want the next topic? Try Pass Statement, Range(), List Comprehensions, or Functions. Just tell me! π