for / while else doesn't make sense

Steven D'Aprano 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:
>>     do_something()
>>     if condition:
>>         break
>>     if another_condition:
>>         break
> 
> But that loop has 3 exits, written in two different ways. Why the special
> case?


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
iterator?

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
value:

for x in [1, 2, 3]:
    print(x, end='')

# 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:
       break
   process(x)


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
dump core.

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):
        process(x)
        if i == biggest:
            break


but I leave dealing with iterators as an exercise for the masochistic.


-- 
Steven



More information about the Python-list mailing list