for / while else doesn't make sense
steve at pearwood.info
Sat Jun 4 05:27:44 EDT 2016
On Sat, 4 Jun 2016 01:41 pm, Lawrence D’Oliveiro wrote:
> On Saturday, June 4, 2016 at 2:22:18 PM UTC+12, Steven D'Aprano wrote:
>> and a loop with two or more exits a *trivially different* way:
>> for x in seq:
>> if condition:
>> if another_condition:
> But that loop has 3 exits, written in two different ways. Why the special
Is that a serious question? Are you really questioning the need for
for-loops to stop iterating when they reach the end of the sequence or
I'll give you the benefit of the doubt and assume you're not trolling.
A for-loop without "the special case" as you put it, would be an infinite
loop that loops forever unless you explicitly checked for an undefined
for x in [1, 2, 3]:
# prints 1 2 3 UNDEFINED UNDEFINED UNDEFINED UNDEFINED ...
meaning practically every loop would have to be written as:
for x in seq:
if x is UNDEFINED:
But at least now you don't have the cognitive burden of remembering that
for-loops are intended to loop over a finite number of items, then stop.
Alternatively, we could just have the for-loop raise an exception when it
passes the end of the sequence. For extra programming machismo, have it
Thus the programmer would be responsible for (somehow!) determining how many
times it is safe to loop. This wouldn't be too onerous for sequences:
biggest = len(seq) - 1:
if biggest > -1:
for i, x in enumerate(seq):
if i == biggest:
but I leave dealing with iterators as an exercise for the masochistic.
More information about the Python-list