Python Mastery – From Basics to Brilliance / Control Flow & Decision Making

else with loops

In Python, you can attach an else block to both for and while loops.

🔸 The else block runs only if the loop finishes normally (without hitting a break).


🔧 Syntax

for item in iterable:
    if condition:
        break  # If this happens, else will NOT run
else:
    # Runs only if loop wasn’t broken
    print("Completed without break!")

🔍 Why Use It?

  • To know if a loop ran till the end without being interrupted

  • No need for extra flags or conditions

  • Cleaner code — especially useful in search tasks


💡 Real-Life Example: Searching a List

names = ["Alice", "Bob", "Charlie"]

for name in names:
    if name == "David":
        print("Found David!")
        break
else:
    print("David not found.")  # ✅ This runs only if David wasn't found

If David were in the list, the break would run and skip the else.


🔁 Works with while Loop Too

x = 0
while x < 5:
    if x == 6:
        break
    x += 1
else:
    print("Exited without break")  # ✅ This runs because break never happened

🧠 Real-Life Analogy

You’re searching your house for your lost keys:

  • Found them in the 3rd room? → You stop searching (break), no celebration (else skipped).

  • Checked all rooms, still no keys? → You sigh and say “Well, not here.” (else runs)


✅ Summary

Feature

Description

else on loops

Runs only when loop completes fully (no break)

Useful for

Clean search, validation, or check patterns

Works with

Both for and while

Pythonic

Yes! Very unique to Python