The "loop and a half"

john polo jpolo at mail.usf.edu
Wed Oct 4 09:44:47 EDT 2017


On 10/3/2017 5:08 PM, Stefan Ram wrote:
> Steve D'Aprano <steve+python at pearwood.info> writes:
>> On Wed, 4 Oct 2017 04:45 am, Rhodri James wrote:
>>> On 03/10/17 18:29, Stefan Ram wrote:
>>>> Is this the best way to write a "loop and a half" in Python?
>>> Define "best".
>> I'd start with "define loop and a half".
>    I encountered this phenomenon decades ago. But only
>    some years ago, I heard someone using a special word
>    for it! Let me try to find it ...
>
>    Yes, it was Mehran Sahami who used it, possibly in one of
>    his lectures of the course "Programming Methodology"
>    (CS 106A) at "Stanford Engineering".
>
>    
>    ...
>
>    The history of this problem goes way back into the past.
>    In the 1950s (and possibly still inthe 1960s), such mundane
>    loops were research topics, and Knuth and others wrote
>    research articles about how to write such a loop in such a
>    way that no test or statement has to be repeated.
>    (I sometimes liked to read old magazines from those years.)
>
>    Thanks for all the answers so far!

I'm adding to what Stefan wrote, simply to point out how a newb like me 
came across this issue formally, besides actually dealing with this in 
my practice.

In Python Programming Fundamentals 2nd ed., the author, Kent D. Lee, 
brings up loop and a half in ch. 3, Repetitive Tasks (p. 82). He wrote:

"Whether you are writing code in Python or some other language, this Reading
Records From a File pattern comes up over and over again. It is 
sometimes called
the loop and a half problem. The idea is that you must attempt to read a 
line from the
file before you know whether you are at the end of file or not. This can 
also be done
if a boolean variable is introduced to help with the while loop. This 
boolean variable
is the condition that gets you out of the while loop and the first time 
through it must
be set to get your code to execute the while loop at least one."


best,

John




More information about the Python-list mailing list