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:If you have multiple
breaks, putprint(n)in a function so you Don’t Repeat Yourself.