replacing `else` with `then` in `for` and `try`

bartc bc at freeuk.com
Mon Nov 6 06:37:50 EST 2017


On 06/11/2017 02:28, Steve D'Aprano wrote:
> On Sat, 4 Nov 2017 03:57 pm, Michael Torrie wrote:

>> Can you be more specific? What are some of these "many" ways of aborting
>> a loop?  Help a guy out here.
> 
> Aside from more exotic methods such as os.abort, os._exit and signal handlers,
> the common ways of breaking out of a loop are:
> 
> - raise
> - return
> - break
> 
> Am I being pedantic? Of course I am. But we're programmers -- if we don't have
> an accurate and complete understanding of code, who will? Given how many
> people find it difficult to understand the semanics of for...else, I think we
> need to be pedantic about it.

Take this for-loop:

     for I in R:
         A
     else:
         B
     C

Here are the various ways of exiting the loop, with Y or N indicating 
whether that particular block (or 'suite') is executed:

                               B       C

   Normal termination:         Y       Y
   Break from A:               N       Y
   Raise/return/etc from A:    N       N

Here, we're only interested in whether B and C have different entries, 
as that would be the only reason to have an 'else' part in the first place.

And that only happens when the loop is terminated with a Break. Unless 
someone knows of any other circumstances where B is not executed but C 
is. (Both B and C also contain raise, return, exit(), infinite loops 
etc, but that shouldn't effect this point.)

Break inside the loop can also be conditional (I think it has to be if 
you want more than one iteration!), which means that sometimes, it will 
never break, then you get the Y/Y (or N/N) result. But the expectation 
is that there the break COULD be executed, so you will need the 'else'.

-- 
bartc



More information about the Python-list mailing list