A couple of weeks ago, I agreed to facilitate a workshop on Python for non-programmers in the cognitive science department at Carleton. It’s been alright so far for the first two sessions - about seven-ish people attending, but with wildly varying skill levels. Specifically, one guy is experienced with C/C++ and several others know almost nothing at all about programming. It’s been hard to engage everyone at once. There’s been a lot of “we can talk about this after” and “this is interesting but probably not important to most of you”… especially from me because I get excited and hope they will still understand.
Anyway! This evening I was trying to find good code examples to show in an online Python interpreter that doubles as a visual debugger. Looking through the available examples, under the advanced Python features section, I saw an example called “for-else” (the title of this post links directly to it). Wait… what is that?
As it turns out, this exists in Python. I found a blog post on the topic that shows a useful application of the technique. This can be applied to a for loop or a while loop, and the code in the “else” clause only runs if the loop exits normally. In other words, it runs if you don’t break out of the loop. In a way, it’s kind of like the “else” is attached to all the break statements inside your loop - namely, if none of the break statements are reached, run the else clause. I have a really hard time matching up the idea of this meaning with an interpretation of “else” - to me, this seems more like a “finally” clause that is surpassed by break. finally is used for exception handling in Java, but by definition you can’t pass over it - code in a “finally” clause is run no matter what. Well, I think. I’m sure there are loopholes I don’t remember, probably involving destructors somehow because they’re a source of much evil.
I feel like it’s a solution in search of a problem, which is probably why this isn’t a very well known feature. Off the top of my head, the only thing I use break for is when I’m looking for a single thing in a collection and want to do something with it afterwards - and not do anything with the rest of the collection. continue is a different story - I use continue a lot more often, because looking at an item of a collection and doing nothing with it is a lot more common than finding one item and discarding the rest of the collection.
But hey, there you go, some unique semantics (I think?) in a programming language. If it was really such a great idea, it probably wouldn’t be so rare.