"for" with "else"?

John Roth newsgroups at jhrothjr.com
Wed Oct 1 06:55:09 EDT 2003


"Andrew Dalke" <adalke at mindspring.com> wrote in message
news:f%reb.10797$NX3.1826 at newsread3.news.pas.earthlink.net...
> John Roth:
> > I don't see what exceptions have to do with it. There are three
> > special ending cases: with break, empty sequence and sequence
> > exhausted. Empty sequence is the only one that isn't handled easily.
>
> Could you give an example of when you would actually use an
> 'empty_sequence' in the real world?  It's never been a problem
> for me (that I can recall) where that distinction was important.

I can recall writing a fair number of loops a while back where
knowing that I had an empty sequence was important. More
recently, I have concentrated on making things simply work
if a sequence is empty. I think that's much better programming
practice when you can accomplish it. However, the days when
I thought I was Joe Superprogrammer are long in my past,
and while I don't have a current example, I've got enough
examples from my past that I can't say I could eliminate all
of them.

One example that comes to mind is the case where you
don't want to send a message at all if there are no instances;
for example, if you are doing a build, the case of no failures
is distinct from the case that there were failures. You want to
do two totally different things. Add the wrinkle that it may not
be easy, convenient or possible to test for an empty sequence
first (think some forms of generator) and I think you can come
up with a number of cases.



> > What I'd like to see is a more general exit clause that also
> > applies to the while statement. Something like:
> >
> > on break:
> > on normal_exit:
> > on empty_sequence:
> > on body_not_executed:
>
> Aren't 'empty_sequence' and 'body_not_executed' identical?

Yes, they are. One is more expressive with the for statement,
and the other with the while statement.

>
> Could you give examples using each one?
>
> What about code which uses a return in the block?  Is
> that counted under 'break'?

I hadn't thought about it. I'd consider it a break.

> What about raising an exception?

That should be handled with a try / except block.
I don't see any reason for new syntax.

John Roth

>
>                     Andrew
>                     dalke at dalkescientific.com
>
>






More information about the Python-list mailing list