I'd like a different name for for "for's" else.
I've been using method/function redefinition in place of conditionals related to initialization.
I'd like a different name for for "for's" else.
I've been using method/function redefinition in place of conditionals related to initialization.
Inside any loop are a conditional and a jump. In pseudocode:
if not <loop end condition> then
<do loop things>
<jump to top of loop>
else //loop is done
<do things in the case that the loop has terminated naturally>
If we 'break' in the body of the loop for some reason, we will never hit the 'else' in this chunk of code. As Mr. Hettinger explains, this is obvious to anyone reading Knuth or coming from a 'goto' style of control flow. This is not an insult, but an observation. (Un)Fortunately, structured programming is the absolute norm now, and we learn looping constructs directly, rather than learning 'goto' and then building to looping constructs. Especially in a language with rich iteration protocols, such as Python, it is very much unapparent that the looping constructs are fancy wrappers around 'goto'.Link to the talk: https://youtu.be/OSGv2VnC0go?t=948
>When used with a loop, the else clause has more in common with the else clause of a try statement than it does with that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs.
In a for loop, the else clause only runs if the loop successfully completes (isn't broken), so the else in for-else means the total opposite of what it means in every other pattern.
I think it would make a lot more sense if it were replaced with "done" or "upon" or something else that communicates how it works.
Edit: This is wrong. See replies.
However, that's exactly how it doesn't work and that's my point. The else clause is only ran if the loop DOESN'T break.