- Home
- Interview Questions
- Python
- How does the else clause work with for and while loops in Py…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: The else block attached to a for or while loop runs only when the loop finishes normally, without hitting a break. If the loop exits through break, return or an exception, the else block is skipped.
Detailed explanation
Most languages only use else with if. Python also allows it on loops. The name confuses many people, so think of it as no-break: the code under else runs when the loop was never interrupted.
- for loop:
elseruns after the iterable is fully used up. If the iterable is empty, the body never runs, butelsestill runs, because nobreakhappened. - while loop:
elseruns when the condition becomes false. If the condition is false at the very start,elseruns immediately. - break: skips the
elseblock completely. - continue: has no effect on
else. It only moves to the next iteration. - return, raise or an uncaught exception: leave the loop and the function, so
elsedoes not run.
The main use case is a search loop. You go through items looking for something, break when you find it, and put the not-found handling in else. Without this feature you would need a flag variable such as found = False, set it inside the loop, and check it afterwards. Loop-else removes that flag and keeps the related logic together.
Inside nested loops, the else belongs to the loop at the same indentation level. A break in the inner loop only affects the inner loop's else.
Example
# 1. Search without a flag variable
def find_user(users, target_id):
for user in users:
if user['id'] == target_id:
print('Found:', user['name'])
break
else:
print('User not found')
users = [{'id': 1, 'name': 'Asha'}, {'id': 2, 'name': 'Ravi'}]
find_user(users, 2) # Found: Ravi
find_user(users, 5) # User not found
find_user([], 1) # User not found (empty list, else still runs)
# 2. Prime check with nested loops
for n in range(2, 10):
for d in range(2, n):
if n % d == 0:
print(n, 'is not prime')
break
else:
print(n, 'is prime')
# 3. Retry logic with while-else
attempts = 0
while attempts < 3:
attempts += 1
if connect(): # assume connect() returns True or False
print('Connected')
break
else:
print('Failed after 3 attempts')
In example 3, the message Failed after 3 attempts prints only if every attempt failed. A successful connection triggers break and skips it.
Common mistakes
- Thinking else runs when the loop body never executes. It runs whenever there was no
break. That includes empty iterables, but it also includes loops that ran every iteration. - Thinking else runs only on success. It is the opposite in search loops. Finding the item usually means
break, soelsehandles the not-found case. - Wrong indentation. Placing
elseat the same level as anifinside the loop turns it into an if-else, which changes the logic silently. - Expecting continue to skip else. Only
break,returnand exceptions skip it.
Follow-up questions
- How would you rewrite a loop-else using a flag variable, or using
any()ornext()? - What happens to the
elseblock if an exception is raised and caught inside the loop body? - How does
elseon a loop differ fromelsein atrystatement?
Interview tip: Say "else on a loop means no break happened" in one line, then show the search example. That gives a precise and practical answer.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More easy Python questions
Related Questions
- In what order do try, except, else and finally blocks run in Python? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
- What is exception chaining in Python and when should you use raise from? · Python · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- Why does using a mutable default argument like a list cause bugs in Python? · Python · 1 ans
- How do positional-only (/) and keyword-only (*) parameters work in Python function signatures? · Python · 1 ans
- What is broadcasting in NumPy and what rules decide whether two arrays can be combined? · Python · 1 ans
- Why does Pandas raise SettingWithCopyWarning and how do you fix chained assignment correctly? · Python · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)