Python for-else and while-else Explained: break, continue and 7 Tested Examples
You search a revision list for Python. If it is present, stop searching. If it is absent, print a message only after every item has been checked. Python can express that last step with an else attached to a loop. It looks unusual because many beginners have only seen else attached to if.
This Proof Lab separates normal completion, break and continue through small programs. Run each block separately in Python 3. All shown outputs were executed and checked before publication.
1. What does loop else mean?
for loop runs when its iterable is exhausted without a break. The else block of a while loop runs when its condition becomes false. A break in that loop skips its else. A return or an uncaught exception can also leave before else is reached.The else is aligned with the loop, not with an if inside it. Indentation determines which statement owns the block. Read loop else as "the loop finished normally", not as "the condition inside if was false once".
2. A search flow you can trace
Loop starts / next check
|
Another item? (for)
Condition true? (while)
/ \
No Yes
| |
Run loop else Run body
| |
| +---------+---------+
| | | |
| break continue body ends
| | | |
| skip else +----+----+
| | |
| | next loop check
+------+----> after whole loop
return / exception leaving loop:
leave this path; else is not reached3. Search succeeds: break skips else
topics = ["SQL", "Python", "OS"]
for topic in topics:
print("check", topic)
if topic == "Python":
print("found")
break
else:
print("not found")
print("after loop")Checked output:
check SQL check Python found after loop
The loop checks SQL, then Python. The break exits this for loop. Its else block is skipped, but the statement after the loop still runs.
4. Search fails: exhaustion runs else
topics = ["SQL", "OS"]
for topic in topics:
if topic == "Python":
print("found")
break
else:
print("not found")Checked output:
not found
Every item is checked and none matches. The iterable is exhausted without a break, so the else block reports the unsuccessful search. No separate found flag is needed.
5. An empty list still reaches else
for topic in []:
print(topic)
else:
print("no break occurred")Checked output:
no break occurred
The body never starts, but the iterable is already exhausted. There was no break, so else runs. Loop else does not mean that the body must run at least once.
6. continue skips an iteration, not else
for number in [1, 2, 3]:
if number == 2:
continue
print(number)
else:
print("finished")Checked output:
1 3 finished
continue skips the remaining body for number 2. It does not terminate the loop. After number 3 the loop is exhausted normally and else still runs.
7. while else follows a false condition
attempts = 0
while attempts < 3:
attempts += 1
print("attempt", attempts)
else:
print("limit reached")Checked output:
attempt 1 attempt 2 attempt 3 limit reached
The condition becomes false after the third attempt, so the else block runs. A break inside this while would skip it. Keep updates before any continue that could otherwise bypass them.
8. break belongs to the inner loop
for row in [1, 2]:
for column in [1, 2]:
print(row, column)
break
else:
print("inner completed")
else:
print("outer completed")Checked output:
1 1 2 1 outer completed
Each inner loop breaks after its first column, so its else is skipped. The outer loop itself never breaks. It visits both rows and then runs its own else.
9. return leaves the function, not only the loop
def find_topic(topics):
for topic in topics:
if topic == "Python":
return "found"
else:
return "not found"
print(find_topic(["Python", "OS"]))
print(find_topic(["SQL"]))Checked output:
found not found
A return exits the function immediately, so no later loop else is reached on the successful call. The second call exhausts the list and returns from else. In this function the final return could also be written after the loop; choose the clearer form for your team.
10. break, continue and normal completion compared
| Event | Next step | Loop else? |
|---|---|---|
| for has no items left | Finish the loop normally | Yes |
| while condition is false | Finish the loop normally | Yes |
| break in this loop | Leave this loop | No |
| continue | Begin the next iteration/check | Not skipped by continue alone |
| return | Leave the function | Not reached |
| Exception that leaves this loop | Transfer control to an exception handler | Not reached |
11. Boundary lab: six ways to leave or continue
Run this block separately. A caught exception inside the body does not by itself prevent normal completion. An exception that leaves the loop does. Compare the inner if else with the loop else by their indentation.
print('1. Initially false while:')
while False:
print('body')
else:
print('else without any iteration')
print('2. Exception caught inside the loop:')
for divisor in [0, 2]:
try:
print(10 // divisor)
except ZeroDivisionError:
print('caught; continue')
continue
else:
print('normal completion; else runs')
print('3. Exception leaves the loop:')
try:
for divisor in [0, 2]:
print(10 // divisor)
else:
print('loop else')
except ZeroDivisionError:
print('caught outside; loop else was not reached')
print('4. False test inside the body is not completion:')
for number in [1, 2]:
if number == 2:
print('match')
break
else:
print('if else: non-match')
else:
print('loop else: no match')
print('5. A while break skips else:')
attempts = 0
while attempts < 3:
attempts += 1
if attempts == 2:
print('found at', attempts)
break
else:
print('no result')
print('after while')
print('6. The continue-to-break practice:')
for number in [1, 2, 3]:
if number == 2:
break
print(number)
else:
print('finished')Executed output:
1. Initially false while: else without any iteration 2. Exception caught inside the loop: caught; continue 5 normal completion; else runs 3. Exception leaves the loop: caught outside; loop else was not reached 4. False test inside the body is not completion: if else: non-match match 5. A while break skips else: found at 2 after while 6. The continue-to-break practice: 1
Trace the two search outcomes
| Input/check | Action | Loop state | Else? |
|---|---|---|---|
| SQL, then Python | Check SQL; check Python; break | Stops at Python | Skipped |
| SQL, then OS | Check both; request next item | Iterator exhausted | Runs once |
| Empty list | Request first item | Already exhausted | Runs once |
| Initially false while | Test condition | Body never entered | Runs once |
Loop else is not a per-item failure branch. It belongs after the full sequence of checks. If the only goal is a Boolean membership test, "Python" in topics is often simpler. Use the loop when each item needs work or the search must stop at a richer condition.
12. Common exam mistakes
- Printing "not found" inside the body after the first non-match. A later item may still match. Put the failure result after the complete search.
- Indenting else under if instead of aligning it with for. Those are different programs.
- Assuming any inner break skips every outer else. A break exits only the innermost enclosing loop.
- Treating continue as break. Continue can still allow normal completion later.
- Forgetting that an empty iterable or initially false while condition can run else immediately.
Use loop else when it makes a search or a retry result clearer. It is optional, not a badge of better Python. A named Boolean flag can be easier for a team unfamiliar with this syntax.
13. Exam questions with short answers
Q. When does for else execute?
When the iterable is exhausted without a break in that loop.
Q. Does an empty for loop run else?
Yes. Its iterable is already exhausted.
Q. Does continue skip loop else?
No. It skips the rest of one iteration, not the whole loop.
Q. Which loop does break terminate?
The innermost enclosing for or while loop.
Q. When does while else execute?
When the condition becomes false, including before the first iteration.
Q. How do you identify whether else belongs to if or for?
Check indentation: it aligns with the statement it belongs to.
Q. What does a return inside a loop do?
It exits the function, so the loop else is not reached.
Q. Does a caught exception always skip loop else?
No. If it is handled inside the body and the loop completes normally, else still runs.
Q. Is loop else the same as the else inside an if?
No. An if else can run for each non-match. A loop else runs once after normal completion.
Q. Does the statement after the whole loop run after break?
Yes, if nothing else transfers control away. Break skips the loop else, not the statement after the whole loop.
Try before checking
In the continue example, replace continue with break. Predict the output before running it. Answer: only 1 is printed. The loop breaks on 2, so neither 3 nor "finished" is printed.
Comments
Post a Comment