5 ms·
It’s consistent with try…else and if…else so I actually think it’s ok.
by AlphaSite 5y ago
It’s consistent with try…else and if…else so I actually think it’s ok.
- 63 5y ago"else" usually means "instead of" or "otherwise" in those patterns. If the original case doesn't run, then the else case runs instead. 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.
- jermy 5y agoThe way you describe is how it worked in zope templates (allowing a 'no items here' text if there was nothing to iterate over in a list) - it was frustrating that the later python implementation was different.
- ptx 5y agoYou could read it as "either process all of these elements, or otherwise do this other thing". If we break, we're not processing all of the elements (the normal case), so we do the "else" part instead. Edit: This is wrong. See replies.
- 63 5y agoThat would make total sense if it were correct. That's exactly how I think most people would intuit it 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.
- ptx 5y agoHmm! Yes, you're right. Even though I knew exactly how it works and I sometimes use it, I still got confused, so maybe it is a confusing feature after all. :)
- housecarpenter 5y agoIt depends on whether you think of the break as success or failure. When I write a loop with a break it's usually some kind of search where the break happens once you've found something, and in that case the break is more of a success.