1.5.2 for: else:

Gordon McMillan gmcm at hypernet.com
Tue Jul 27 22:43:00 EDT 1999


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]
> class neverMind(): pass
> 
> try:
>  for x in [1,2,3]:
>   print x
>   if x == 2: raise neverMind
> except neverMind:
>   print "modern else clause here"

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

Or will you now claim that:

lst = [1,2,3]
for i in range(len(lst)):
  if lst[i] == 2: break
if i == len(lst):
  print "Tanksley else clause here"

is a better solution <wink>?

insufferably-sanctimoniously-y'rs

- Gordon




More information about the Python-list mailing list