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

Derek Thomson derek at wedgetail.com
Thu Jun 20 05:24:16 EDT 2002


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

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.




More information about the Python-list mailing list