[Tutor] for/else question
Jeff Shannon
jeff at ccvcorp.com
Fri Sep 12 13:27:41 EDT 2003
Scott Widney wrote:
> 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.
This is true, this usage of 'else' doesn't quite match English syntax,
and Python is usually pretty good about trying to match English usages
where practical. This is one of the features that makes Python so
easy to read.
However, I think it'd be *more* confusing to have two different
keywords that do almost the same thing. Python declines having a
"do...while" loop for that reason -- the do-loop part can be fairly
easily expressed as a while loop, and thus would be needless duplication.
Speaking of while loops, 'else' works with them also --
>>> x = 0
>>> while x < 5:
... print x
... x += 1
... else:
... print "That's all, folks!"
...
0
1
2
3
4
That's all, folks!
>>>
In this case, the usage of 'else' is quite a bit closer to the
standard English usage -- "While x is less than 5, do one thing;
otherwise, do this other thing." Now, if you look at that, and then
look at the comparable for loop ...
>>> for x in range(5):
... print x
... else:
... print "That's all, folks!"
...
0
1
2
3
4
That's all, folks!
>>>
The parallel structure is obvious, and it makes it hard to argue that
'else' should be called something else in this one particular case.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list