1.5.2 for: else:

Fredrik Lundh fredrik at pythonware.com
Wed Jul 28 16:11:10 EDT 1999


William Tanksley <wtanksle at dolphin.openprojects.net> wrote:
> >    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.

you can say what you want, but it isn't defined
that way; the language reference says:

    "If all expressions are false, the suite of
    the else clause, if present, is executed." 

    (where "all expressions" are the expressions
    for all if/elif clauses in the statement)

if you continue reading, you'll find:

    "if the expression is false (which may be
    the first time it is tested) the suite of the
    else clause, if present, is executed"

and

    "when the items are exhausted (which is
    immediately when the sequence is empty),
    the suite in the else clause, if present, is
    executed"

for ALL these statements, the else clause is exe-
cuted if and only if ALL controlling expressions
evaluate to FALSE.

> >    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".

huh?  the "else" clause isn't involved in the loop's
termination at all; it's executed when the con-
trolling expression becomes false.  if you raise
an exception, or use the break statement, or
return to the caller, you don't end up in the
"else" clause by a very simple reason:  the con-
trolling expression isn't false.

> >    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.

huh?  the "else" clause is part of the if/while/for
statement. the code that follows the loop isn't.

I repeat:

for ALL these statements, the else clause is exe-
cuted if and only if ALL controlling expressions
evaluate to FALSE.

whether blocks are executed or not isn't part
of the definition; only the conditions are.

> I expect consistency, and I expect that the major features (else with if
> and else with catch) will define consistency, not minor features like else
> with looping.

you have consistency.  for-else and while-else works
EXACTLY like if-else.  for ALL these statements, the
else clause is executed if and only if ALL controlling
expressions evaluate to FALSE.

you can argue as much as you want, but that's the
way it is.  you gotta live with it (unless you have your
own time machine, of course ;-)

</F>





More information about the Python-list mailing list