The "loop and a half"

Steve D'Aprano steve+python at pearwood.info
Wed Oct 4 11:35:16 EDT 2017


On Thu, 5 Oct 2017 12:44 am, john polo wrote:

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

No it doesn't. Who is this Kent Lee, and is he actually fluent in Python?
Because the following problem doesn't seem like it:


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

Utter nonsense. There's no "must" here. I'll accept the remote possibility
that maybe one time in a million you have to do what he says, but the other
999999 times you just read from the file in a for-loop:

for line in file:
    process(line)


> 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."

I've been programming in Python for twenty years, and I don't think I have
ever once read from a file using a while loop.



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