β›”πŸ”„ 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 += 1

2. 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)
        break

5. 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! 😊