If/then style question

Steve Holden steve at holdenweb.com
Fri Dec 17 11:46:56 EST 2010


On 12/17/2010 11:13 AM, Tim Golden wrote:
> On 17/12/2010 15:53, Steve Holden wrote:
> 
> [... snip example of for-else ...]
> 
>> This construct appears to be unpopular in actual use, and when it comes
>> up in classes and seminars there is always interesting debate as people
>> discuss potential uses and realise there are useful applications.
> 
> I use this not infrequently, and I like it when it seems to be an
> elegant way to express the code path. But I still misremember from
> time to time and assume that the "else" clause fires when the for
> loop is empty.
> 
Yes, that's a common misconception. The classical use is something like

    for item in possibilities:
        if item == target:
            break
    else:
        raise NotFound("Didn't find it")

Though of course arguably that logic might be expressed in other ways,
such as

    if target not in possibilities:
        raise NotFound("Didn't find it")

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon 2011 Atlanta March 9-17       http://us.pycon.org/
See Python Video!       http://python.mirocommunity.org/
Holden Web LLC                 http://www.holdenweb.com/




More information about the Python-list mailing list