1.5.2 for: else:

Donn Cave donn at u.washington.edu
Tue Jul 27 19:33:58 EDT 1999


wtanksle at dolphin.openprojects.net (William Tanksley) writes:
|On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:
|>On Tue, Jul 27, 1999 at 04:15:44PM +0400, Oleg Broytmann wrote:
|
|>|    The following program:
|>| ----------
|>| for a in ['a', 12]:
|>|    print a
|>| else:
|>|    print "Empty!"
|>| ----------
|
|> http://www.python.org/doc/current/tut/node6.html#SECTION006200000000000000000
|
|> 4.4 break and continue Statements, and else Clauses on Loops 
|
|> Loop statements may have an else clause; it is executed when the loop
|> terminates through exhaustion of the list (with for) or when the condition
|> becomes false (with while), but not when the loop is terminated by a break
|> statement. 

| Well, I'm suprised.  I had also expected the else clause to run on empty
| loop.  It seems so natural, in line with the meaning of a loop (loop on
| this; otherwise do that).
|
| Fortunately I've never actually used it and thus been disenchanted.

[(I'm confused? else clause _does_ execute after an empty loop, like
   for x in ():
       pass
   else:
       print 'for else'
)]

It seems to me to work the only useful way, so you almost can't
go wrong - at worst, if you mistake its meaning, you won't use it.
That may not be the same thing as "natural", but it's close.
It's one of the neat little things that make me pause for a moment
of appreciation when I get to use it.

| Understanding the current semantics seems to require understanding the
| nature of loop tests in Python.  Since I understand them I can agree that
| this makes sense, but I'm still a bit leery, because you're not 'elsing'
| on the data but rather on code inside the loop.
|
| I would _definitely_ use exceptions to handle this.

Note that "try/except" also takes an "else", which also happens to have
the only useful sense and executes when the try block executes with no
exception.  It's handy for code that should execute in the normal case
but does not itself need to be enclosed in an exception handler, so you
can focus the try block more precisely on the section that needs it.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu




More information about the Python-list mailing list