4 ms·
The else makes perfect sense. The for loop keeps going as long as the condition is true. When the condition is false, it exits the loop without breaking. Else a
by georgyo 8y ago
The else makes perfect sense. The for loop keeps going as long as the condition is true. When the condition is false, it exits the loop without breaking. Else acts on the condition being false.
- Nition 8y agoBut the else fires in Python if the loop does not break. It sounds like you're saying the opposite. Even if you aren't, I think we can agree it's potentially confusing.
- georgyo 8y agoThis is the correct place for it to do so. Break skips the check entirely. If the for loop exits normally, the condition was false.
- Nition 8y agoYou understand that it can be a confusing code construct though, right? Even in your comments I'm kind of confused at your meaning because you said: > When the condition is false, it breaks. And then you said: > If the for loop exits normally, the condition was false.
- georgyo 8y agoI have updated that comment, a normal loop exit is not the same as a break. I can understand how it can be confusing, but the inverse would not make any sense. Another way to look at a for loop is a fancy while loop that sets a variable by some function. Every loop iteration that function is ran. If the function fails, the loop exits. This is infact how they work. https://anandology.com/python-practice-book/iterators.html#the-iteration-protocol https://anandology.com/python-practice-book/iterators.html#t... If next() fails, that is when the loop exits.
- deleted 8y ago[deleted]
- Myrmornis 8y agoWhat you say implies that you’d be happy with while(condition()): ... else: ... But that makes even less sense since `while` is semantically like an `if` with continuation. GP is right, it’s rarely used, because the syntax clashes with the natural reading of the code.
- detaro 8y agowhile ... else is a good comparison, yes. and it exists exactly like that in python: if the condition check turns false, the else branch is executed.