else clauses in while and for loops

Ralph Corderoy ralph at inputplus.demon.co.uk
Sun Apr 2 13:31:21 CEST 2000


Hi,

> > I don't think that is a real need.
> 
> so?  do you suggest that we should remove it, and force people to
> rewrite their perfectly working pro- grams, just to make you happy?
> or maybe we could use all that energy to work on something more
> important?

I suggest you go back and read my post properly.  In particular, the
original poster's request.

> > Please give some examples showing the real need for else clauses in
> > this context.

Someone replied giving a pointless use of else.  I said out that this
was a pointless use of else and therefore didn't match the original
poster's request of an example `showing the real need'.

I didn't say there wasn't a real need for else, I said `I don't think
that is a real need' immediately after quoting the pointless example.


Ralph.


-------- Original post follows

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