[Tutor] Making a Primary Number List generator

Marc Tompkins marc.tompkins at gmail.com
Thu May 16 03:17:34 CEST 2013


On Wed, May 15, 2013 at 5:07 PM, Steven D'Aprano <steve at pearwood.info>wrote:


> Guido's time machine strikes again.
>
>
> py> import sys
> py> sys.stdout.write('NOBODY expects the Spanish Inquisition!\n')
> NOBODY expects the Spanish Inquisition!
> 40
>
>
> The write() method of file objects in Python 3 return the number of
> characters written.
>

Awesome!  Thank you Steven; I don't need it today but I suspect I will
shortly.

Meanwhile, for tutees following along at home and wondering what that was
all about: when you do this in an interactive session, as above, it's
confusing.
When you use it in the course of a program, your program doesn't "see" what
gets printed; it only "sees" what gets returned by the function.  So you
would use the return value something like this:

import sys
outString = "NOBODY expects the Spanish Inquisition!\n"
if sys.stdout.write(outString) == len(outString):
    print("We're good")
else:
    print("Oopsie!")

In other words, if the value returned by write() is the same as the length
of the object you passed to it, the write operation was successful;
otherwise there was a problem and you need to deal with it.

Notice also that you don't _have_ to do anything with the return value; if
you don't assign it to something, or compare it to something (as I did in
my example) it just gets garbage collected and disappears.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130515/77e329e2/attachment-0001.html>


More information about the Tutor mailing list