Friday Finking: Contorted loops

Alan Gauld alan.gauld at yahoo.co.uk
Fri Sep 10 07:38:26 EDT 2021


On 09/09/2021 22:36, dn via Python-list wrote:

> Even in fairly modest Python constructs, we quickly repeal the one-in,
> one-out philosophy because try...except operates by providing another
> exit-path.

Exceptions are exceptional by their nature (or should be!) As such
they can arguably be excused from the SP strictures.

But python complicates this tenet still further by adding an else
clause to its loops. And complicating this still more is that these
else clauses have almost exactly opposite effects.

while...else...

executes the else if the body of the loop does NOT get executed.

for...else...

executes the else iff ALL iterations of the for loop DO complete.

This confuses beginners immensely - and quite a few non
beginners too; which is probably why they are not often
seen "in the wild".

This adds to the question of where exactly does a Python loop
end? Is it after the code-suite following the loop construct?
Or is it after the else code-suite, where such exists?

Returning to the specific case of a repeat structure.
In the case of a while loop the else offers another option:

while condition
    loop-body
else
    loop-body

Now loop-body always gets executed at least once. But at
the cost of duplicating the loop-body code, thus violating DRY.

Just another thought...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Python-list mailing list