Ned Batchelder: Loop Like A Native

Steven D'Aprano steve+python at pearwood.info
Sat Aug 6 23:42:50 EDT 2016


On Sun, 7 Aug 2016 08:05 am, Lawrence D’Oliveiro wrote:

> On Saturday, August 6, 2016 at 12:08:30 PM UTC+12, bream... at gmail.com
> wrote:
>> A couple or three years old but this is well worth seeing for anybody,
>> regardless of your Python expertise.
>> http://nedbatchelder.com/text/iter.html
> 
> A loop like
> 
>     for i in ... :
>        ...
>        if ... cond ... :
>            break
>        ...
>     #end for
> 
> actually has two different ways to terminate. Is there any good reason for
> them to be written two different ways?

Yes. The two ways of ending the loop are distinct and different:

- reach the end, and stop;
- bail out early.


When you read a book, there are two ways of stopping:

- reach the end, and run out of pages to read, so you stop;
- give up reading early, and just put the book away.

(Or possibly throw the book across the room.)


Why would you treat these two cases in the same way?

interested = True
for page in book:
    if interested:
        read(page)
    if bored_now():
        interested = False
    
finished = False
while not finished:
    try:
        page = next(book)
    except StopIteration:
        finished = True
    else:
        read(page)
        if bored_now():
            finished = True



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list