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

Fredrik Lundh fredrik at pythonware.com
Thu Jun 20 05:28:00 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?

    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>





More information about the Python-list mailing list