for what are for/while else clauses

F

Fredrik Lundh

Erik said:
Where's the controlling condition in

for x in sequence:
...
else:
...

?

you mean you don't know how the for-loop checks if there's
another item in the sequence?

(hint: look for StopIteration in the docs)

</F>
 
A

Alexander Schmolck

Alex Martelli said:
Python could presumably help a little by warning about an 'else' on
a for or while loop that contains no 'break' statements. But the
reason Python's for/else and while/else statements are not intuitive
to most people can be boiled down to identifying that "controlling
condition" -- the fact that the 'controlling condition' is "a break
statement has executed" is """hardly obvious or most particularly "the
only obvious" interpretation""", to repeat myself:).

Hmm, I can't see the break here:
.... else: print 'nothing'
....
nothing

(Not that I wouldn't argue that the semantics of else in loops are blindingly
obvious, but I can see the (albeit slightly strained) analogy with if/else).

'as
 
J

Just

the fact that the 'controlling condition' is "a break statement
has executed"

that's not how it works.[/QUOTE]

But it is: the only time the else clause is _not_ executed is when the
loop was stopped due to a break statement:
... print x
... else:
... print "else"
...
else
... print x
... else:
... print "else"
...
1
else
... print x
... break
... else:
... print "else"
...
1
You're either speaking in tongues, or you're wrong. Am I missing
something?

Just
 
A

Alex Martelli

Fredrik said:
the condition that controls if the conditional part of the statement
is executed. from what I can tell, that's the usual definition.

We agree that it is the usual definition. We appear to disagree that
focusing on that condition is a sensible way to present (e.g.) the way
while/else works. E.g., consider:

.... print avalue,
.... avalue += 1
.... else:
.... print 'else here'
....

versus
.... print avalue,
.... avalue += 1
.... if something(avalue, another): break
.... else:
.... print 'else here'
....

When somebody else "will the else clause execute", I would answer
(for the first case) "yes [if the loop ever terminates]" -- and for
the second case, "if and only if the break does not execute [i.e.,
if the 'something' test is never satisfied while the controlling
condition holds]".

In the first case, it would make no difference whatsoever to
recode the loop as:

while avalue < another:
print avalue,
avalue += 1
print 'foo here'

Again, "foo here" gets printed (as long as the loop ever terminates).

But in the second case, where a guarded 'break' is involved, the
transliteration is not feasible (you'd have to add a 'flag' variable
in order to remove the 'else' and keep the same semantics).

It seems misleading to me to focus on the controlling condition, i.e.,
on whether "avalue < another" is still true, or not. In the second
version of the loop it may perfectly well be true that the controlling
condition is false when the predicate 'something' is satisfied --
nevertheless, if the predicate is satisfied and thus the break
executes, the "else" clause does not execute.

In a for/else or while/else construct, the only way to make your
assertion true is to define "the controlling condition" as "a break
[or return] interrupted the for or while loop [or an exception was
propagated]" -- basically (quibbles on returns and exceptions apart)
just what I said about "no break was executed".

for a while-statement, the controlling condition is the test at
the top.

for a for loop, the condition is "is there another item" (to quote the
language reference: "When the items are exhausted (which is imme-
diately when the sequence is empty) ... the loop terminates.".

for a try-except clause, the condition is "did the suite raise an
exception".
the fact that the 'controlling condition' is "a break statement
has executed"

that's not how it works.

In practice, it is (for both while and for, not for try; and net of
the already-interpolated distinguos about returns and exceptions).

When there is no 'break' in the loop's body, the 'else' clause is
useless: the body of the else clause would execute under exactly the
same conditions (i.e., if the loop ever terminates normally, w/o
return or exceptions) if the same statements were placed right after
the loop's end, rather than in an 'else' clause. The only practical
reason to ever have an 'else' clause on a for or while is to do
something different for a loop that terminates with a break, rather
than terminating "normally". Focusing on the 'break' being present
and executing therefore seems more practical to me, than focusing on
the "controlling condition" (which may be false without this fact
causing the 'else' clause to execute -- if a break intervenes).


Alex
 
F

Fredrik Lundh

But it is: the only time the else clause is _not_ executed is when the
loop was stopped due to a break statement:

the break statement has nothing to do with the else clause; the else
is executed when there's no more item in the sequence. if you break
or raise or return or yield-and-never-resume or call-and-never-return
your way out of the loop doesn't matter.

read the C code if you don't believe me.
You're either speaking in tongues, or you're wrong. Am I missing
something?

like Alex, you're confusing cause and effect. don't do that; things are
easier to understand if you explain how they actually work.

</F>
 
A

Alex Martelli

Alexander said:
Alex Martelli said:
Python could presumably help a little by warning about an 'else' on
a for or while loop that contains no 'break' statements. But the
reason Python's for/else and while/else statements are not intuitive
to most people can be boiled down to identifying that "controlling
condition" -- the fact that the 'controlling condition' is "a break
statement has executed" is """hardly obvious or most particularly "the
only obvious" interpretation""", to repeat myself:).

Hmm, I can't see the break here:
for x in []: print 'something'
... else: print 'nothing'
...
nothing

Exactly because there is no 'break' in the loop's body, the 'else: '
clause-header is useless in this case; the code:

for x in []: print 'something'
print 'nothing'

(where the second print follows the whole loop rather than being
the body of its 'else' clause) would be quite equivalent.
(Not that I wouldn't argue that the semantics of else in loops are
blindingly obvious, but I can see the (albeit slightly strained) analogy
with if/else).

If I squint hard enough I can see the similarity, sure, but I keep
thinking that "how do I _USE_ this language feature" is a more generally
useful viewpoint than "how is this language feature implemented". And
the (modest) _usefulness_ of the else clause on for and while loops is
inevitably connected to the possibility that a 'break' in the loop's
body may execute. If there is no such possibility, you might as well
just code the statements right after the whole loop, rather than putting
them in an else clause.


Alex
 
B

Bengt Richter

Hi,

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?

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



waiting for enlightment,
My mnemonic is to think of the mysterious elses as coming after prefixed pseudo-code like:

if this_code_is_interfered_with:
<loop code or try block>
else: # got to end of loop or end of try block without interference

hence
... else: print 'got to end of nothing without interference ;-)'
...
got to end of nothing without interference ;-)
... except: pass
... else: print 'got to end of try: without interference.'
...
got to end of try: without interference.
... if raw_input('break? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asdad
break? asad
while> asdasd
break?
while>
got to end of while w/o interference
... if raw_input('break? ')=='y': break
... else: print 'got to end of while w/o interference'
...
while> asd
break? y

Regards,
Bengt Richter
 
E

Erik Max Francis

Fredrik said:
you mean you don't know how the for-loop checks if there's
another item in the sequence?

(hint: look for StopIteration in the docs)

This hardly seems like a very good mnemonic, since the for...else
construct predates iterators.

The whole point here is that the behavior of for...else isn't
intuitively obvious. Sure, you can rationalize it after the fact, but
you have to be familiar with that rationalization to claim it makes
intuitive sense.

In the face of language rejections like try...except...finally,
for...else does not at all seem like something that is intuitively
obvious. (There's no doubt it's useful, but it's hardly transparent.)

--
Erik Max Francis && (e-mail address removed) && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \
\__/ It's only love that gets you through
-- Sade
 
F

Fredrik Lundh

Mel said:
Interesting way to think about it. Thanks.

So in some sample code:

while some_condition:
some_action ()
else:
last_action ()
following_code ()

If the loop results in some_action being done, say, 17
times; then that means that some_condition was found true 17
times. The 18th time, some_condition is found to be false,
the else takes effect and last_action gets done one time.

imagine a dialect of Python that supports C-style goto's and labels.
in this dialect,

while some_condition:
some_action ()
else:
last_action ()

can be rewritten as

this_statement:
if some_condition:
some_action ()
goto this_statement
else:
last_action ()
next_statement:

(which, of course, is exactly what Python's current compiler does, but
on the bytecode level).

"break" and "continue" can now be rewritten as "goto next_statement"
and "goto this_statement".

for "for-in" and "try-except", the code calculating the "some_condition"
value is a bit different, but the rest works in exactly the same way.

here's the for-in version:

<set up the iterator>
this_statement:
<fetch next value from iterator>
if <value found>:
variable = <value>
some_action ()
goto this_statement
else:
last_action ()
next_statement:

and here's the try-except version (somewhat simplified):

this_statement:
<enable error handling>
some_action ()
error_handler:
<disable error handling>
if <matching error occurred>:
some_action ()
else:
other_action ()
The only wrinkle then is that the while loop construct
passes control to the following code after that one
last_action. But we expect that from a while loop.

most Python statements pass control to the next statement
when they're done.
The effect of a break in the suite controlled by the
while is to blow away execution of the whole while
construct, including the else.

As an explanation, I like it.

me too.

</F>
 
M

Magnus Lyck?

Fredrik Lundh said:
the break statement has nothing to do with the else clause; the else
is executed when there's no more item in the sequence. if you break
or raise or return or yield-and-never-resume or call-and-never-return
your way out of the loop doesn't matter.

On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

....will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement
is just noise: an extra line of code and additional whitespace
for the following statement(s).

It's only together with the python idiom of breaking out of
loops with ifs (which is considered bad form in some (non
python) circles that the else part of the for and while statements
make sense.
 
A

Aahz

On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

...will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement is just
noise: an extra line of code and additional whitespace for the
following statement(s).

While technically correct, I don't think you could claim that it's "just
noise" in this example:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
else:
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(record)
 
M

Magnus Lyck?

On the other hand, I only think it's in the case of a break
in block that...

while condition:
block
else:
print "Loop finished"

...will behave differently than...

while condition:
block
print "Loop finished"

So, unless you use a break in the block, the else statement is just
noise: an extra line of code and additional whitespace for the
following statement(s).

While technically correct, I don't think you could claim that it's "just
noise" in this example:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
else:
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(record)

First of all, I'm not sure it's a good idea to use
exceptions like a poor (rich?) man's GOTO like this. :)

If you persist, I'm not so sure your code is clearer than:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(record)

With the else clause on the for loop, just after the if
statement, you are bound to confuse people. I would guess
that most people who casually looked at that code would
think that you had made an indentation mistake. Some would
probably "correct" it.
 
M

Michele Simionato

First of all, I'm not sure it's a good idea to use
exceptions like a poor (rich?) man's GOTO like this. :)

If you persist, I'm not so sure your code is clearer than:

try:
for ORlist in includes:
try:
for filter in ORlist:
for field in curr_fields:
for item in record[field]:
if match(item, filter):
raise Found
raise NotFound
except Found:
continue
except NotFound:
continue
else:
result.append(record)

With the else clause on the for loop, just after the if
statement, you are bound to confuse people. I would guess
that most people who casually looked at that code would
think that you had made an indentation mistake. Some would
probably "correct" it.

I, for one, could get confused. BTW, I don't remember a single case in
all my code where I have used so much indentation. I would write some
helper function and avoid nesting as much as possible.

Michelee
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,152
Latest member
LorettaGur
Top