else clauses in while and for loops

Fredrik Lundh effbot at telia.com
Tue Apr 18 03:11:58 EDT 2000


Jeff Massung <jmassung at magpiesystems.com> wrote:
> >Yes, but if you look at the examples, they also use "break".  After a
> >loop, "else" basically means "if no iteration of the loop met the
> >conditions to break out."  It's a common usage, where in C we'd compare
> >the final loop index with the maximum (or whatever) loop index to see
> >if the loop ran all the way through.
>
> I don't think that I'm following you, give me an example where the loop
> ends, but the else wouldn't be executed and I think I'll better
understand.

how about reading the fine manual?

    http://www.python.org/doc/current/ref/while.html

    "A break statement executed in the first suite terminates
    the loop without executing the else clause's suite."

examples have been given earlier in this thread, but here's
another one:

        s = list_of_strings

        for i in range(len(s)):
            if s[i] == something:
                break
            else:
                print "didn't find anything"
                raise ValueError

        print "index is", i

> >your paragraph would justify better on the right margin, too!  Seriously,
> >"else" does invariably execute if the loop was never run once, but as
> >mentioned above it also executes in other circumstances.
>
> I think it would be better suited if it didn't execute under "other
> circumstances". It would be nice to know _exactly_ when it would execute,
> and only under 1 or 2 conditions (maybe that is the way it is now, I just
> don't see it).

"if", "for", "while", and "try" all execute their "else" suite if
and only if the controlling condition is tested and found to
be false.

for "if" and "while", the controlling condition is the given
expression.  if evaluated, and found to be false, the "else"
suite is executed.

for a "for" statement, the controlling condition is "is the
sequence exhausted?".

for a "try/except" statement, it is "did an exception occur
in the try suite?".

statements like "break", "return", and "raise" can be used to
terminate loops without testing the condition.

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list