1.5.2 for: else:

Vadim Chugunov chega_ at yahoo.com
Wed Jul 28 20:08:07 EDT 1999


How about this:

8<---------------------------------
class Item:
    def __init__(self,key):
        self.key = key

seq= [Item(1),Item(2),Item(3)]

for item in seq:
    if item.key==42:
        break
else:
    item = Item(42) # oh well, append() does not return a value
    seq.append(item)

print item.key
8<---------------------------------


Stidolph, David <stidolph at origin.ea.com> wrote in message
news:11A17AA2B9EAD111BCEA00A0C9B41793034AAC5B at molach.origin.ea.com...
>
> Please show your example using the else .. I'd like to see it.
>
> -----Original Message-----
> From: Vadim Chugunov [mailto:chega_ at yahoo.com]
> Sent: Wednesday, July 28, 1999 4:58 PM
> To: python-list at cwi.nl
> Subject: Re: 1.5.2 for: else:
>
>
> I would say that else: clause after a loop is really related to the if:
> controlling the break,
> rather than to the loop itself.
>
> When I first saw Python syntax for loops I said: "A-ha!  So in Python I will
> not
> need a goto
> in situations like this:
> -----
> for(Item* pitem=pseq->First(); pitem; pitem=pitem->Next())
>     if (pitem->key==42)
>         goto Found;
>
> pitem = pseq->Insert(new Item());
> Found:
>     // use item pointed to by pitem
> -----
> In fact, I do not see any other good use for else: clause in a loop.
> Maybe the docs should just explicitly say what this feature is good for ?
>
> Vadim







More information about the Python-list mailing list