3 ms·
In fact, what it means is "execute this else when the loop guard fails" (regardless of whether the loop body has executed at all, or how many times). It is a le
by kazinator 8y ago
In fact, what it means is "execute this else when the loop guard fails" (regardless of whether the loop body has executed at all, or how many times). It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails.
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".
- acqq 8y ago> It is a legitimate alternate clause in the sense that it provides alternative behavior when the guard fails. 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"