1.5.2 for: else:

William Tanksley wtanksle at dolphin.openprojects.net
Tue Jul 27 20:15:20 EDT 1999


On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 14:29:43 +0200, Thomas Wouters wrote:

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

>Maybe it violated your expectations, but it's much more valuable than 
>what you expected. After all, testing for an empty sequence is a 
>no-brainer. But finding a match in a list, and testing whether you 
>fell off the end without finding one, is (without the else clause) a 
>much messier proposal.

First of all, meeting expectations is one reason why I like Python, and
therefore to me is a very valuable quality.  I would go so far as to say
that it's more valuable than any amount of utility to people who have
learned and happen to remember the shibboleth.

I would also disagree with you that my interpretation would result in
disutility: you'd merely have to use exceptions instead of 'break'.  This
is more in line with the way the rest of Python works, and makes the
effect of the abnormal termination of the loop perfectly clear.

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.

Pretty odd, eh?

class neverMind(): pass

try:
 for x in [1,2,3]:
  print x
  if x == 2: raise neverMind
except neverMind:
  print "modern else clause here"

>- Gordon

-- 
-William "Billy" Tanksley




More information about the Python-list mailing list