[Tutor] for/else question
Scott Widney
SWidney at ci.las-vegas.nv.us
Fri Sep 12 11:48:55 EDT 2003
> I seem to recall a discussion of this on comp.lang.python some time
> ago, which intimated that it was included as much for symmetry (with
> if/else) as for practical need. (The implementation of code suites
> is such that it is essentially free -- 'else' works the same whether
> it follows a 'for' or an 'if'.)
>
> That said, I can see cases where it's important to know whether
> you've broken out of a loop or not. You might need to take an
> action only if there are no errors in your loop, for instance.
> You could use a sentinel variable, but it's cleaner to avoid that,
> and for/else allows you to avoid it.
This is probably a moot point (I doubt that they would change this) but I
think it's the use of the word 'else' that is confusing. Here is how I tend
to think of the 'if' statement:
If a condition is true:
then do something;
otherwise:
do something else.
This is not symmetrical with 'for: else:' in my mind. Grammatically
speaking, it seems backward, and therein lies the tension. Here is my brain
map of the 'for' statement:
For each item in a group:
do something;
afterwards (provided nothing went wrong):
do this too.
"Otherwise" doesn't map cleanly to "afterwards". If we swapped the terms we
would get this:
If a condition is true: then do something;
afterwards: do something else.
For each item in a group: do something;
otherwise: do this.
It just doesn't fit. But there is a term in another statement in Python that
seems closer to what I'm thinking:
Try:
something that might not work;
if it fails:
do this;
finally (whether or not it worked):
do this too.
This "feels" more comfortable. Finally and afterwards are semantic
neighbors. So if I think 'finally' in my head, but type 'else' when dealing
with a for statement, it seems to relieve the pressure. And now we return to
our regularly scheduled program....
Scott
More information about the Tutor
mailing list