Skip to content

Module 6 · Loops and Iteration — topic 11 of 12

Loop else clauses

Python loops can have an else block that runs only when the loop finishes without break. Learn how it works for for and while loops and why it is ideal for search loops.

Intermediate 10 min read·Lesson 80 of 306 in Python Programming

Learning objectives

  • Explain when a loop’s else block runs
  • Use for-else for search results
  • Decide when a flag variable is clearer

Definition

Python loops can have an else block that runs only when the loop finishes without break. Learn how it works for for and while loops and why it is ideal for search loops.

Introduction

Both for and while loops can have an else clause. Despite the name, it doesn’t mean “if the loop didn’t run”. It means “if the loop ended normally, without hitting break”.

Why it matters

Search loops have two outcomes: found (break) or not found (loop ran to the end). The else clause handles the “not found” case directly, without an extra flag variable.

Detailed explanation

for ... else: the else block runs after the loop has gone through every item without break.

while ... else: the else block runs when the condition becomes false, but not if the loop was left with break.

If break runs, the else block is skipped entirely.

If the loop body never runs at all (empty list, condition false at the start), the else still runs, because no break happened.

A return or an exception inside the loop also skips the else.

Some programmers find loop-else unfamiliar. A clear comment such as # no break: not found helps, and a flag variable is an acceptable alternative when it reads better.

A useful way to remember it is to read the else as “no break”: for ... no break: handle the case where nothing stopped the loop early.

Syntax

Text
for item in items:
if matches(item):
break
else:
# runs only if no break happened
handle_not_found()
  • else is aligned with for or while.
  • It runs when the loop completes normally.
  • break skips it.

Code examples

Found or not found

Python
for word in ["apple", "kiwi", "plum"]:
if word.startswith("k"):
print("Found:", word)
break
else:
print("No word starts with k")
Output
Found: kiwi

The else runs when there is no break

Python
for word in ["apple", "plum"]:
if word.startswith("k"):
break
else:
print("No word starts with k")
Output
No word starts with k

More examples

Prime check with for-else

Python
def describe(n):
if n < 2:
return f"{n} is not prime"
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
return f"{n} is divisible by {d}"
else:
return f"{n} is prime"
for n in [1, 2, 15, 17, 49]:
print(describe(n))
Output
1 is not prime
2 is prime
15 is divisible by 3
17 is prime
49 is divisible by 7

Step-by-step explanation

  • Numbers below 2 are handled first by a guard clause.
  • The loop only checks divisors up to the square root of n, which is enough to find a factor.
  • Finding a divisor returns immediately, which also skips the else.
  • If no divisor is found, the else returns the “prime” message. For n = 2, range(2, 2) is empty, so the else runs straight away.

Expected output

Running “Prime check with for-else” prints exactly:

TextOutput
1 is not prime
2 is prime
15 is divisible by 3
17 is prime
49 is divisible by 7

Practical applications

  • Validation loops report “all checks passed” in the else clause.
  • Retry loops report “gave up” in a while-else after the attempts run out.
  • Search routines print “not found” without a separate flag.

Best practices

  • Use loop-else for search loops with break.
  • Add a short comment explaining the else.
  • Use a flag variable if your team finds it clearer.

Common mistakes

Thinking else means “loop didn’t run”

Avoid

Expecting the else to run only for an empty list.

Prefer

It runs whenever the loop ends without break, including after a full run.

The else is tied to break, not to whether iterations happened.

Indenting else inside the loop

Avoid

for x in items:
if x == t:
break
else:
print("not found")

Prefer

for x in items:
if x == t:
break
else:
print("not found")

Indented under the loop it becomes the if’s else and prints for every non-matching item.

Key takeaways

  • A loop’s else runs if the loop finishes without break.
  • break, return or an exception skip it.
  • It is ideal for “not found” handling in searches.

Try it yourself

  1. 1
    Use for-else to print whether a list contains any negative number.
  2. 2
    Write a while-else that allows 3 password attempts and prints “Locked” in the else.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic