The else clause is only executed after the while condition is evaluated to be false.
Thus, if you break out of the loop, or if an exception is raised, the else won't be executed (since the while condition has not been evaluated to be false yet).
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
Answer from ars on Stack OverflowThe else clause is only executed after the while condition is evaluated to be false.
Thus, if you break out of the loop, or if an exception is raised, the else won't be executed (since the while condition has not been evaluated to be false yet).
One way to think about it is as an if/else construct with respect to the condition:
if condition:
handle_true()
else:
handle_false()
is analogous to the looping construct:
while condition:
handle_true()
else:
# condition is false now, handle and go on with the rest of the program
handle_false()
An example might be along the lines of:
while value < threshold:
if not process_acceptable_value(value):
# something went wrong, exit the loop; don't pass go, don't collect 200
break
value = update(value)
else:
# value >= threshold; pass go, collect 200
handle_threshold_reached()
The else clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is not executed if you break or return out of a block, or raise an exception. It works for not only while and for loops, but also try blocks.
You typically find it in places where normally you would exit a loop early, and running off the end of the loop is an unexpected/unusual occasion. For example, if you're looping through a list looking for a value:
for value in values:
if value == 5:
print "Found it!"
break
else:
print "Nowhere to be found. :-("
While loops can have an else statement!
Examples of the while...else or for...else constructs in the wild?
Why do for loops have an else block?
For/else, while/else, try/else.
Videos
Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable
This will execute when the while condition is false but not if you break out of the loop early.
For example:
Using flag
nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0
while i < len(nums):
if nums[i] == target:
found = True
print("Found:", target)
break
i += 1
if not found:
print("Not found")Using else
nums = [1, 3, 5, 7, 9]
target = 4
i = 0
while i < len(nums):
if nums[i] == target:
print("Found:", target)
break
i += 1
else:
print("Not found")Maybe I'm the only one who didn't know this, but you can put an else statement after a while loop which will be used if the while loop is never entered. I found this out on the Leetcode problem of the day for today when I tried putting an else after my while loop, mostly expecting an error but typing because it's what I wanted the code to do, and it ran! The code I used is below. I know there are more optimal solutions, but I'm happy with what I learned today.
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
n = len(temperatures)
answers = [0] * n
stack = []
for i in range(n):
while len(stack) > 0 and temperatures[i] > stack[-1][1]:
answers[stack[-1][0]] = i - stack[-1][0]
stack.pop()
else:
stack.append([i, temperatures[i]])
if len(stack) == 0:
stack.append([i, temperatures[i]])
return answers