So now when I use it, I always put a comment next to it for myself and the next person:
for item in items:
if found:
break
else: # no-break
print('not found.')So now when I use it, I always put a comment next to it for myself and the next person:
for item in items:
if found:
break
else: # no-break
print('not found.')If there's anything I've learned, it's that just because a language has a feature, doesn't mean it should be used.
You shouldn't use a feature just because a language has it, you should use it because it's a simple, well-defined primitive that's less complex than alternatives.
Except when the loop is infinite, or is broken prematurely, the loop guard will fail. Under for item in list, the implicit guard fails immediately when the list is empty. If the list isn't empty, it fails after the last item is iterated upon.
Thus here it also means "else if there are no more items to be processed".
But the "guard fails" and the else is executed on every normal loop exit, except if the exit was done with break.
for a in range( 1,3 ):
print( a )
else:
print( "end" )
gives: 1
2
end
It's an "alternative" only when there's break. In all other cases it is executed.Even naming it "nobreak" would be confusing as without break it is always executed at the end. The clearer naming would be approximately "on_every_nonbreak_end_of_for"
It does though http://codepad.org/en4mzowh