1.5.2 for: else:

William Tanksley wtanksle at dolphin.openprojects.net
Wed Jul 28 15:39:47 EDT 1999


On Tue, 27 Jul 1999 21:43:00 -0500, Gordon McMillan wrote:
>William Tanksley wrote:
>> On Tue, 27 Jul 1999 18:35:10 -0500, Gordon McMillan wrote:

>> >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.
>[rant]
>> I would also disagree with you that my interpretation would result
>> in disutility: you'd merely have to use exceptions instead of
>> 'break'.  
>[more rant]

>--------billy.py--------------------
>class neverMind: pass

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

>for x in [1,2,3]:
> print x
> if x == 2:
>  break
>else:
> print "Hi Billy!"
>---------------------------------------------------

>C:\TEMP>python billy.py
>1
>2
>modern else clause here
>1
>2

>C:\TEMP>

>Notice the difference?
>You need to raise the exception if you've gone through the loop and 
>not found 2. The best way to do that <snicker> is with an else 
>clause.

Sure do!  In spite of the fact that I actually did understand the modern
meaning of 'else', in practice I manage to screw it up anyhow.  I can
choose to make this a commentary on my programming skill, OR on the
obtuseness of the current definition of 'else'.  Hmm, which to choose,
which to choose...

:)

However, you're wrong about the best way to detect a 2 in the list using
this style.  To steal the same example:

try:
 for x in [1,2,3]:
  print x
  if x == 2: raise neverMind
 print "modern else clause here"
except neverMind: print "found two"
else:
 print "another place to put the modern else clause"

Wow, TMTOWTDI.  Oops, did I say the wrong thing?

Of course, by demonstrating both ways to do it, I'm making the code more
complex; but you can see that this solution solves the problem quite
elegantly.

The place to use MY definition of 'else', OTOH, is when you're building a
structure during the iteration, but the result of an empty loop is
different than the initial value the variable has to have when going
through the loop.

Here you go.  This example might convert a Python list into a Lisp
tree-list -- but to imitate Lisp (okay, it's a toy problem, I'm cheating)
an empty list produces NIL ~= None.

var = Node(None,None)
for x in pyList:
  var.car = x
  var.cdr = Node()
else:
  var = None

>insufferably-sanctimoniously-y'rs

>- Gordon

unstoppably-confidantly y'rs

-- 
-William "Billy" Tanksley




More information about the Python-list mailing list