Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

'else' clause in 'for' and 'while'

0 views
Skip to first unread message

Ville Vainio

unread,
Jun 20, 2002, 5:07:36 AM6/20/02
to
How do you people use the else clause in for and while constructs? Are
they used widely for some specific applications? Do they offer
elegant, idiomatic solutions to some problems?

I haven't found any use for them yet myself, but knowing that they
exist and still not using them troubles me, core python being quite
'small' after all.

-- Ville

Derek Thomson

unread,
Jun 20, 2002, 5:24:16 AM6/20/02
to

It's good for searching, and saves mucking about with flags to achieve
the same effect. For example:


for item in list:
if item == match:
# Item found, take some action
item_found(item)
break
else:
# Item not found, take some other action
item_not_found()


Regards,
Derek.

Fredrik Lundh

unread,
Jun 20, 2002, 5:28:00 AM6/20/02
to
Ville Vainio wrote:
> How do you people use the else clause in for and while constructs? Are
> they used widely for some specific applications? Do they offer
> elegant, idiomatic solutions to some problems?

for item in list:
if item == my_target:
print "found it"
process(item)
break
else:
print "not found"

while more_items():
item = get_next_item()
if item == my_target:
print "found it"
process(item)
break
else:
print "not found"

try:
item = lookup(database, key)
except KeyError:
print "not found"
else:
print "found"
process(item)

try:
handler = getattr(object, "handler")
except AttributeError:
print "no handler"
else:
handler(event)

# (etc)

</F>


0 new messages