[Tutor] for/else question

Raymond Hettinger python at rcn.com
Thu Sep 11 23:57:44 EDT 2003


> So... yeah... Do /you/ use "else" with for loops? If so, when?

Yes.
Here's an except from a relevant article in PyZine:

"""
The for statement syntax is "for target in sequence: suite [else suite]". The semantics are clear – the else clause is run after
the loop if no break statements are encountered. The purpose for the optional else clause may not be as obvious.

In the 1970’s debates about Structured Programming, fierce discussion about eliminating goto statements revealed situations where
there were no adequate substitutes using structured constructs such as for and while [3]. One of those cases involved being able
to tell (after the requisite single entry and exit points) whether a loop had run to completion or had been broken. An optional
else clause provided a structured solution:

    for element in itemlist:
        if element is target:
            <actions when target is found>
            break
        else:
            <actions when target is not found>
    <actions taken whether or not target is found>


. . .

[3] Structured Programming with goto Statements, Donald Knuth, 1974.
"""


Raymond Hettinger




More information about the Tutor mailing list