else clauses in while and for loops

Ralph Corderoy ralph at inputplus.demon.co.uk
Mon Mar 27 14:50:44 EST 2000


> > 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.




More information about the Python-list mailing list