for -- else: what was the motivation?

Weatherby,Gerard gweatherby at uchc.edu
Mon Oct 10 10:52:51 EDT 2022


Core developer Raymond Hettinger explains the history starting at 15:40 https://www.youtube.com/watch?v=OSGv2VnC0go

(which I found on stackoverflow https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops )

TL:DR
The “else” is a historical artificial from the way developers thought during the transition from unstructured (i.e. “GOTO”) programming to structured programming. Since we all do structured now, it seems odd.


From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Calvin Spealman <cspealma at redhat.com>
Date: Monday, October 10, 2022 at 10:38 AM
To: python-list at python.org <python-list at python.org>
Subject: Re: for -- else: what was the motivation?
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On Sat, Oct 8, 2022 at 5:35 PM rbowman <bowman at montana.com> 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")
>

I wonder if for/else could have been less confusing if it was referred to
as for-break-else and if the else clause was only valid syntax if the for
loop actually contained a break statement in the first place.

--

CALVIN SPEALMAN

SENIOR QUALITY ENGINEER

calvin.spealman at redhat.com  M: +1.336.210.5107
[image: https://urldefense.com/v3/__https://red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$<https://urldefense.com/v3/__https:/red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$>  ] <https://urldefense.com/v3/__https://red.ht/sig__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihhXbt2Z5$  >
TRIED. TESTED. TRUSTED. <https://urldefense.com/v3/__https://redhat.com/trusted__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihjGGi9WT$  >
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihnTgBbx-$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!lSA-VzlSq_UQvMUO2npcFCxacA2jOlt2ZD6LCiwdfMGpYexlKgYpIgDCxlHPs473PNyH7cww2ufihnTgBbx-$>


More information about the Python-list mailing list