1. Home
  2. Interview Questions
  3. Python
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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: else runs after the iterable is fully used up. If the iterable is empty, the body never runs, but else still runs, because no break happened.
  • while loop: else runs when the condition becomes false. If the condition is false at the very start, else runs immediately.
  • break: skips the else block 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 else does 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, so else handles the not-found case.
  • Wrong indentation. Placing else at the same level as an if inside the loop turns it into an if-else, which changes the logic silently.
  • Expecting continue to skip else. Only break, return and exceptions skip it.

Follow-up questions

  • How would you rewrite a loop-else using a flag variable, or using any() or next()?
  • What happens to the else block if an exception is raised and caught inside the loop body?
  • How does else on a loop differ from else in a try statement?

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

All easy questions →

Related Questions

Q1 of 10 · Python
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA