Ned Batchelder: Loop Like A Native
Rick Johnson
rantingrickjohnson at gmail.com
Sun Aug 7 19:19:00 EDT 2016
On Saturday, August 6, 2016 at 10:43:01 PM UTC-5, Steven D'Aprano wrote:
> 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
This algorithm does not exit early when `interested` becomes false, instead, it iterates every page of the book regardless of the value of `interested`. Was this intentional, or merely a mistake?
> finished = False
> while not finished:
> try:
> page = next(book)
> except StopIteration:
> finished = True
> else:
> read(page)
> if bored_now():
> finished = True
That kind of code, whilst being "somewhat" idiomatic python, is horrific. If the intent is to iterate the pages of a book until the end is reached *OR* until the "reader's interest wanes", then a simple for-loop will suffice.
for page in book:
isReaderInterested = reader.read_page(page)
if not isReaderInterested:
break
Simple is better than complex.
More information about the Python-list
mailing list