The "loop and a half"

Grant Edwards grant.b.edwards at gmail.com
Wed Oct 4 13:24:32 EDT 2017


On 2017-10-04, Steve D'Aprano <steve+python at pearwood.info> wrote:

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

You're right, that construct isn't used for reading from files in
Python.  It _is_ commonly used for reading from things like sockets:

mysock.connect(...)
while True:
    data = mysock.recv(9999)
    if not data:
        break
    do_something_with(data)
mysock.close()

-- 
Grant Edwards               grant.b.edwards        Yow! Now I am depressed ...
                                  at               
                              gmail.com            




More information about the Python-list mailing list