control structures (was "Re: Sins")

Colin J. Williams cjw at connection.com
Sun Jan 9 11:35:58 EST 2000


skaller wrote:
> 
> Gordon McMillan wrote:
> 
> > > YUKKKKKK!!! There is no natural way to do this.
> > > We fall through the loop on failure, instead
> > > of success. (using a flag, or testing anything
> > > afterwards, is not acceptable as a solution).
> >
> > 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.

Aside from that.  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."

Illustrative code is appended.

More useful would be to execute the else clause only if the sequence is
empty.  This might be expressed as:

    for x in L:
	...
    otherwise ...

Colin W.

t= [1,2]
for i in t:
  print i
else: print 'else'  
t= []
for i in t:
  print i
else: print 'else'





More information about the Python-list mailing list