for -- else: what was the motivation?

Axy axy at declassed.art
Sun Oct 9 00:37:59 EDT 2022


Got it, thanks!

Actually the reason I never used "else" was the violation of the rule of 
beauty "shortest block first". With if--else you can easily follow this 
rule by inverting "if" expression, but with for--else you can't. The 
loop body of the simplest example is already three lines, in real life 
things are much worse.

So it was probably the first time I used "else" because I had only one 
line in my loop which appended data packets to the buffer and if "else" 
behaved as I thought it would meant I have no more data and could just 
return early, terminating outer loop with no other boolean logic.

I have no idea why I thought so, some language might had such a 
semantic. Maybe my own I developed 20 years ago, but I could not invent 
that by myself, I definitely had some source of inspiration.

Python is awesome because it's semantic is clear for the majority, but 
there are places that look odd. In case of "for", "else" looks logically 
tied with "for" clause, but actually it is not. It's tied with "break" 
statement and I overlooked that even after re-reading the language 
reference. If "else" was named like "never_broken_loop" or "nobreak", 
the semantic would be perfectly clear. But, what's done is done.

I guess the real motivation was avoiding moving such patterns to a 
separate functions, say, "find_banana" where early returns make "else" 
absolutely unnecessary.

Cheers.

Axy.


On 08/10/2022 06:49, rbowman wrote:
> On 10/7/22 21:32, Axy wrote:
>> So, seriously, why they needed else if the following pieces produce 
>> same result? Does anyone know or remember their motivation?
>
> In real scenarios there would be more logic in the for block that 
> would meet a condition and break out of the loop. If the condition is 
> never met, the else block runs. To steal from w3schools:
>
>
> fruits = ["apple", "peach", "cherry"]
> for x in fruits:
>   print(x)
>   if x == "banana":
>     break
> else:
>   print("Yes we got no bananas")
>
>


More information about the Python-list mailing list