else clauses in while and for loops

William Park parkw at better.net
Mon Mar 27 16:51:49 EST 2000


On Mon, Mar 27, 2000 at 08:50:44PM +0100, Ralph Corderoy wrote:
> > > Please give some examples showing the real need for else clauses in
> > > this context.
> >
> > def lookup(stringList, word):
> >     """Finds the first instance of word in stringList. Returns -1 if not
> > found"""
> >     i = 0
> >     while i < len(stringList):
> >         if stringList[i] == word:
> >             break
> >         i = i + 1
> >     else:
> >       # is only executed if we never hit that break
> >         return -1
> >     return i
> 
> I don't think that is a real need.  Wouldn't it normally be written to
> return ASAP rather than jump through hoops.
> 
>     def lookup(stringList, word):
> 	i = 0
> 	while i < len(stringList):
> 	    if stringList[i] == word:
> 		return i
> 	    i = i + 1
> 	return -1
> 
> Ralph.

True.  But, using "else" avoids having to deal with a local variable to
find out how it left the loop.

--William




More information about the Python-list mailing list