On Wed, Jul 22, 2020 at 1:15 PM Paul Sokolovsky firstname.lastname@example.org wrote:
On Wed, 22 Jul 2020 09:45:31 +1000 Steven D'Aprano email@example.com wrote:
On Tue, Jul 21, 2020 at 10:07:47PM +0100, Barry wrote:
- Because that not what else mean today. Its elif never looped.
py> for x in [1,2]: ... print("inside loop") ... else: ... print("elif never looped") ... inside loop inside loop elif never looped
This is why I have long-argued that the keyword here should be *then* not else. The semantics are that the loop executes, *then* the following "else" block executes,
But no, loop executes, *or else* the following "else" block executes ;-). That's the logic of founding fathers. After one grasped that logic, one comes to appreciate a weird beauty of it. The verdict remains the same though: "Do Not Use".
There's a buggy construct that I see VERY frequently in my students' code (which I'll show in Python syntax here, but this can happen in any language) that closely parallels the actual semantics of Python's for-else, and showcases its value.
# Find the first two-digit number, or return 99 def find_big_number(pile): for number in pile: if number > 10: return number else: return 99
It's extremely common to see this "else" attached to its "if" in a way that prevents the loop from finishing. Now, obviously, in the case where you're using a "return" as the body of the else, you could just unindent it as unconditional post-loop code, but that doesn't work for other examples, and as a general rule, it seems that people like to think in terms of "if it is what we want, do this, otherwise do that".
And that behaviour is exactly what a for-else loop does.