The following Python code will result in n (14) being printed, as the for
loop is completed.
for n in range(15):
if n == 100:
break
else:
print(n)
However, I want the opposite of this. Is there a way to do a for ... else (or while ... else) loop, but only execute the else code if the loop did break?
There is no explicit for...elseifbreak
-like construct in Python (or in any language that I know of) because you can simply do this:
for n in range(15):
if n == 100:
print(n)
break
If you have multiple break
s, put print(n)
in a function so you Don't Repeat Yourself.
A bit more generic solution using exceptions in case you break in multiple points in the loop and don't want to duplicate code:
try:
for n in range(15):
if n == 10:
n = 1200
raise StopIteration()
if n > 4:
n = 1400
raise StopIteration()
except StopIteration:
print n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With