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
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
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
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
8. Difference Between While-Else & For-Else βοΈ
| Concept | While-Else | For-Else |
|---|---|---|
| Runs when loop completes normally | Yes | Yes |
| Skipped when break executes | Yes | Yes |
| Typical use-case | Retries, validation | Searching, flag logic |
| Depends on sequence | No | Yes (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 π
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! π