πŸ”βž‘οΈ Python While-Else & For-Else β€” Understanding Loop Else Blocks

Introduction 🌟

In Python, loops (while and for) can contain an optionalelse block that runs **only when the loop finishes normally**. This means the else runs when the loop condition becomes False or when the loop runs out of items β€” but NOT when a break statement is used.

Note

πŸ’‘ Think of else in loops as β€œNo Break Occurred”.

1. While-Else β€” Basic Example πŸ”„

while_else_basic.py

i = 1

while i <= 3:
    print(i)
    i += 1
else:
    print("Loop finished normally")

βœ”οΈ The else block runs because the loop ended normally (there was no break).

2. While-Else With Break ❌

while_else_break.py

i = 1

while i <= 5:
    if i == 3:
        break
    print(i)
    i += 1
else:
    print("This will NOT run")

Note

⚠️ If break executes, the else block is skipped.

3. Real-World While-Else Example 🌍

Useful when validating attempts or searching repeatedly.

while_else_real.py

attempts = 0

while attempts < 3:
    pin = input("Enter PIN: ")
    if pin == "1234":
        print("Login successful!")
        break
    attempts += 1
else:
    print("Account locked due to too many attempts!")

4. For-Else β€” Basic Example πŸ”

for_else_basic.py

for i in range(3):
    print(i)
else:
    print("Loop completed")

βœ”οΈ The else block runs only after the loop ends naturally.

5. For-Else Used for Searching πŸ”

This is one of the most practical use-cases: Running the else only when the searched item is NOT found.

for_else_search.py

numbers = [10, 20, 30, 40]

search = 25

for n in numbers:
    if n == search:
        print("Found:", n)
        break
else:
    print("Not found!")

Note

βœ”οΈ else runs only when break is NOT triggered.

6. For-Else With Strings πŸ”€

for_else_string.py

word = "python"

for char in word:
    if char == "z":
        print("Character found!")
        break
else:
    print("'z' not found in the word")

7. For-Else With Prime Number Check 🧠

prime_check.py

num = 17

for i in range(2, num):
    if num % i == 0:
        print("Not a prime")
        break
else:
    print("Prime number")

Note

βœ”οΈ One of the most popular real uses of for-else.

8. Difference Between While-Else & For-Else βš–οΈ

ConceptWhile-ElseFor-Else
Runs when loop completes normallyYesYes
Skipped when break executesYesYes
Typical use-caseRetries, validationSearching, flag logic
Depends on sequenceNoYes (iterates over items)

9. Nested Loops With Else πŸͺœ

nested_for_else.py

for i in range(3):
    for j in range(3):
        print(i, j)
    else:
        print("Inner loop completed for i =", i)

10. Important Notes ⚠️

  • else does NOT mean β€œif condition is False”.
  • It means β€œloop ended without break”.
  • Commonly used for searching, login attempts, validation loops.
  • Avoid using else in loops if it makes logic harder to understand.

Conclusion πŸŽ‰

>>β€œLoop else is one of Python’s hidden gems β€” perfect for clean search logic and graceful loop endings.” ✨

You now understand while-else and for-else in Python! Want the next tutorial? Try Range(), Pass Statement, Functions, or List Comprehensions. Just tell me! 😊