The "loop and a half"
bartc
bc at freeuk.com
Wed Oct 4 15:55:06 EDT 2017
On 04/10/2017 14:44, john polo wrote:
> 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."
while not eof(f):
# read next bit of the file
But you need an eof(f) function that tells you if you are at the end of
the file. Some people might be concerned that the status could change
between checking for eof, and doing a subsequent read (but I've never
had such problems).
This is suitable for reading perhaps binary files in uneven chunks,
which are dependent on the last bit read, so iterating over the file by
line or by byte won't work.
--
bartc
More information about the Python-list
mailing list