for what are for/while else clauses

Fredrik Lundh fredrik at pythonware.com
Fri Nov 14 14:41:35 EST 2003


Diez B. Roggisch wrote:

> today I rummaged through the language spec to see whats in the for ... else:
> for me. I was sort of disappointed to learn that the else clauses simply
> gets executed after the loop-body - regardless of the loop beeing entered
> or not.
>
> So where is an actual use case for that feature?

for item in seq:
    if item == target_item:
        print "Found", item
        break
else:
    print "Nothing found, dude!"

> I imagined that the else-clause would only be executed if the loop body
> wasn't entered, so I could write this
>
> for r in result:
>   print r
> else:
>   print "Nothing found, dude!"
>
> instead of
>
> if len(result):
>   for r in result
>     print r
> else:
>   print "Nothing found, dude!"

which is usually written as:

    if result:
        for r in result:
            print r
    else:
        print "Nothing found, dude!"

or

    if not result:
        print "Nothing found, dude!"
    else:
        for r in result:
            print r

</F>








More information about the Python-list mailing list