Enumerate question: Inner looping like in Perl

Alex Martelli aleaxit at yahoo.com
Sun Oct 31 11:09:28 CET 2004


Pekka Niiranen <pekka.niiranen at wlanmail.com> wrote:
   ...
> ...                   try:
> ...                           for i, char in itr:
> ...                                   print 'inner', i, char
> ...                                   if char == 'f':
> ...                                           break
> ...                   except StopIteration:
> ...                           print "f not found"
   ...
> Not working: Iter() takes care of its own exceptions?

Nope.  Rather, the 'for' statement does not propagate the StopIteration
exception that terminates it -- such a propagation would be extremely
disruptive of 99% of Python's programs, and I'm astonished that you
expected it!

What you want is, I believe, among the Tutorial's examples...:

for i, ch in itr:
    print 'inner', i, ch
    if ch == 'f': break
else:
    print 'f not found'

That's what the 'else' clause in a 'for' statement is for: it triggers
when the loop terminates normally (as opposed to ending with a break or
return or by propagating an exception).  The ability to deal with a "not
found" case, where the "found" cases exit by break, is the main use case
of this 'else' clause.

> This recurring feeling that writing REALLY correct programs in Python
> is not easier than in lower level languages... :(

I think that you can get all the info about Python you need for the
purpose (and then some) from "Python in a Nutshell", but of course I'm
biased...;-)


Alex



More information about the Python-list mailing list