1.5.2 for: else:

Vadim Chugunov chega_ at yahoo.com
Wed Jul 28 17:57:55 EDT 1999


I would say that else: clause after a loop is really related to the if:
controlling the break,
rather than to the loop itself.

When I first saw Python syntax for loops I said: "A-ha!  So in Python I will not
need a goto
in situations like this:
-----
for(Item* pitem=pseq->First(); pitem; pitem=pitem->Next())
    if (pitem->key==42)
        goto Found;

pitem = pseq->Insert(new Item());
Found:
    // use item pointed to by pitem
-----
In fact, I do not see any other good use for else: clause in a loop.
Maybe the docs should just explicitly say what this feature is good for ?

Vadim

William Tanksley <wtanksle at dolphin.openprojects.net> wrote in message
news:slrn7pum9t.2ro.wtanksle at dolphin.openprojects.net...
> On Wed, 28 Jul 1999 00:50:14 GMT, Fredrik Lundh wrote:
> >William Tanksley <wtanksle at dolphin.openprojects.net> wrote:
> >> The very worst part of the current else: behavior is that it changes the
> >> meaning of else.  In other constructs, else is an alternate path to take
> >> if the data being tested fails a single expression test.  In this
> >> contruct, else is a path taken if the code block belonging to the previous
> >> test executes a certain instruction.
>
> >nope.  you've got it all backwards.  consider this:
>
> >    for an "if" statement, "else" is a path taken if the
> >    expression evaluates to false.
>
> Close enough -- I would say it's the path taken if the 'if' block isn't
> executed.
>
> >    for a "while" statement, "else" is a path taken if the
> >    expression evaluates to false.  or in other words,
> >    when the loop terminates by natural causes.
>
> In other words, it executes when you'd expect an 'else' to not execute --
> 'else' doesn't mean "natural causes".
>
> >    for a "for" statement, "else" is a path taken when
> >    there are no more elements to loop over.  or
> >    in other words, when the loop terminates by
> >    natural causes.
>
> In addition to the above carping, I have to add that the code following
> the for (or while) loop is what I'd expect to execute after the loop
> terminates.
>
> >not that complicated, was it?
>
> I didn't think it was either, but it seems that in spite of my initial
> understanding, I still managed to reverse it accidentally.
>
> >now, what you seem to have trouble with isn't
> >the "else"-clause -- it's the behaviour of "break":
>
> >"else" always works the same way.  and so does
> >"break".  what else did you expect from Guido?








More information about the Python-list mailing list