← Back

Home β€Ί Problems β€Ί else clause on a for loop

else clause on a for loop

🧠 Predict the output Topic: loops Difficulty: medium Free

What this problem practises

Loops are where off-by-one bugs live. range() excludes its stop value, the loop variable keeps its last value even after the loop ends, and break versus continue changes the flow in ways that are easy to misread when you skim.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: medium β€” expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

numbers = [2, 4, 6, 8]
for n in numbers:
    if n % 2 != 0:
        print("Found an odd number")
        break
else:
    print("All numbers are even")

Understand the rule

Python allows else on a for loop, and its meaning surprises almost everyone: the else block runs when the loop finishes normally β€” that is, without break. It has nothing to do with the loop body being empty or the condition failing. The construct exists for search loops: 'if the loop found something it breaks; else (no break), report not found.'

How to trace it

  1. First determine whether any iteration executes break.
  2. If break fires: the loop ends immediately AND the else block is skipped.
  3. If the loop runs out of items without breaking β€” including the zero-iteration case of an empty iterable β€” the else block runs.
  4. Assemble output: body prints for executed iterations, then the else print only in the no-break case.

Common wrong fixes

Rule to remember

for/else means 'else = no break'. If the loop completed every iteration (even zero of them), else runs; the moment a break fires, it does not.

Solve it in the interactive editor β†’

πŸ” Learning path: Loops

Problem 15 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Loop variable after the loop endsNext in path: Nested loop with a shared variable β†’

πŸ’Ό Learning path: Interview Practice

Problem 6 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Loop variable after the loop endsNext in path: Next problem β†’

More loops problems

Keep going