"also" to balance "else" ?

Ron Adam rrr at ronadam.com
Wed Jun 15 14:07:17 EDT 2005


Fredrik Lundh wrote:
> Ron Adam wrote:
> 
> 
>>So the (my) confusion comes from the tendency to look at it in terms of
>>overall program flow rather than in terms of the specific conditional
>>logic.
>>
>>In a for loop the normal, as in terminating normally, behavior of a loop
>>is one where the loop test evaluates as 'False' ending the loop.  And
>>the abnormal or counter behavior is when a break statement executes.
>>Thus the 'else' block is the normal result, and the skipping the 'else'
>>block becomes the abnormal counter behavior.
> 
> 
> a typical use-case for for-in-else is a search loop:
> 
>     for item in collection:
>         if predicate(item):
>             print "found", item
>             break
>     else:
>         print "not found"
>         return
> 
>     print "use", item
> 
> where your "abnormal behaviour" is, of course, the expected
> behaviour.  if you insist on looking at things the wrong way,
> things will look reversed.
> 
> </F>

It isn't so much as reading it the wrong way, as it is to how it reads 
in the context it is used in.  In the above it works out that the 
negative search result is a successful loop completion, so the else 
reads correctly in that context.

If the context was one of verifying completeness or correctness of a 
collection, then the context would be reversed and the else would 
indicate success instead of failure.

I do see it both ways.  Testing for an item in a list is probably the 
more common occurrence.

If anything, this just points out the error of trying to apply code 
logic to a larger context.  They aren't always the same. It is nice when 
code logic matches the context it's used in, as it makes the code much 
easier to read and understand.

My initial thought of adding 'also' was that it might lead to being able 
to write more code where the code logic more directly parallels the 
context it's used in.  From the few example uses I've found in the 
library, it looks like it wouldn't make that big of a difference.

Maybe someone else can find more uses than I have.  <shrug>  I tried.

Regards, Ron




More information about the Python-list mailing list