control structures (was "Re: Sins")

Gordon McMillan gmcm at hypernet.com
Sun Jan 9 19:17:59 EST 2000


Colin J. Williams wrote:
> 
> skaller wrote:
> > 
> > Gordon McMillan wrote:

[John Skaller expresses disgust with searching a list with 
"for", because he finds needs to use a flag]
> > >
> > > That's the reason that Python has the "for
> > > .. else" construct that William Tanksley
> > > hates so much.
> > >
> > >  for i in X:
> > >    if X[i]==e:
> > >      # do the "found" thing
> > >      break
> > >  else:
> > >    print "Not Found"
> > 
> > That doesn't work. The 'do the "found" thing'
> > is in the wrong place: it must be outside the loop,
> > since it is usually the 'normal continuation'
> > of the routine.

[Colin] 
> Aside from that.  

Aside from what? In the Skaller vocabulary "broken" and 
"doesn't work" mean "are not according to Skaller 
preferences". He likes to think he's shocking people, but he 
has only drained those terms of meaning.

>It seems to me that the weakness of the
>    for ...
>    else 
> structure is that the else clause is executed whether the 
> 'for' succeeds or not. The Language Reference Manual has:
> 
>  "The expression list is evaluated once; it should yield a    
> sequence. The suite is then executed once for each item in the
> sequence, in the order of ascending indices. Each item in turn is
> assigned to the target list using the standard rules for
> assignments, and then the suite is executed. When the items are
> exhausted (which is immediately when the sequence is empty), the
> suite in the else clause, if present, is executed, and the loop
> terminates."

I don't know what you mean by "succeeds". The "else" clause 
is skipped if the loop is terminated.
 
> Illustrative code is appended.
> 
> More useful would be to execute the else clause only if the
> sequence is empty.  This might be expressed as:

As one who regularly uses the searching algorithm above, I 
find it highly useful. I find "if seq:" to be useful for testing for an 
empty sequence. I'm not going to defend the spelling of the 
construct, or it's description in the Language Ref, but it *is* 
very useful.

- Gordon




More information about the Python-list mailing list