[Tutor] Fwd: Trying to enter text from a file to a Dictionary
Ben Markwell
benmarkwell at gmail.com
Sat Jan 28 04:27:49 CET 2006
>
>
> Hi Ben,
>
> Yes, that's the point: Python doesn't know when to stop. *grin*
>
> The way we've rewritten the loop:
>
> while True:
> ...
>
> is an "infinite" loop that doesn't stop unless something in the loop's
> body does something extraordinary, like "breaking" out of the loop.
> Python is much dumber than we might expect.
>
>
> In more detail: Python's readline() method doesn't fail when we reach the
> end of a file: we actually start hitting the empty string. For example:
>
> ######
> >>> import StringIO
> >>> sampleTextFile = StringIO.StringIO("""This is
> ... a sample
> ... text file
> ... """)
> >>> sampleTextFile.readline()
> 'This is\n'
> >>> sampleTextFile.readline()
> 'a sample\n'
> >>> sampleTextFile.readline()
> 'text file\n'
> >>> sampleTextFile.readline()
> ''
> >>> sampleTextFile.readline()
> ''
> ######
>
> Notice that when we hit the end of the file, readline() still continues to
> run and give us empty string values. That's why the loop above needs to
> make sure it breaks out in this particular situation.
>
>
> Does this make sense? Please feel free to ask questions about this.
>
> Yes The -- while true loop -- needs something to be false or it needs to
be told when to stop. If that is correct, then it makes sense.
Thanks
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060127/bc774be2/attachment.htm
More information about the Tutor
mailing list