for / while else doesn't make sense

Steven D'Aprano steve at pearwood.info
Fri Jun 3 23:00:22 EDT 2016


On Sat, 4 Jun 2016 02:24 am, Lawrence D’Oliveiro wrote:

> On Saturday, June 4, 2016 at 3:52:42 AM UTC+12, Rob Gaddi wrote:
>> Lawrence D’Oliveiro wrote:
>> 
>>> The reason why I don’t like this is that there are two ways out of the
>>> Python for-statement, and they are written quite differently. Why the
>>> asymmetry? Logically, all ways out of a loop are of equal significance.
>> 
>> I wouldn't say that at all.  One is early termination due to success.
>> The other is that you've run out of things to try, and exit due to
>> exhaustion of the iterator.  They're two very different cases...
> 
> Different in what way? A loop exit is a loop exit. It causes termination
> of the loop.

You can exit a loop because you have run out of items to process, or you can
exit the loop because a certain condition has been met.

The canonical example is a search, where you need to process differently
depending on whether a match was found or not. In pseudo-code:


for item in items:
    if condition(item):
        # found match, exit loop
        break

if match was found:
    process match
else:
    no match



-- 
Steven



More information about the Python-list mailing list