5

This is probably something stupid I am missing but it has really got me hung up on a larger project (c extension) that I am writing.

Why is print "Hello, World!" passing None and an extra \n to sys.stdout here?

>>> import sys
>>> class StdOutHook:
...     def write(self, text):
...         sys.__stdout__.write("stdout hook received text: %s\n" % repr(text))
... 
>>> class StdErrHook:
...     def write(self, text):
...         sys.__stderr__.write("stderr hook received text: %s\n" % repr(text))
... 
>>> sys.stdout = StdOutHook()
>>> sys.stderr = StdErrHook()
>>> 
>>> def x():
...     print "Hello, World!"
... 
>>> 
>>> print x()
stdout hook received text: 'Hello, World!'
stdout hook received text: '\n'
stdout hook received text: 'None'
stdout hook received text: '\n'
>>> 
chown
  • 51,908
  • 16
  • 134
  • 170

3 Answers3

8

print x() prints the return value of x() which is implicitly None

Either replace print "Hello world" with return "Hello world" or replace print x() with x()

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    OMG, I just realized my `def x()` is printing, not returning.... I am an idiot.. Thank you!! – chown Nov 27 '11 at 20:21
3

Two things:

First, print automatically adds a new line unless you specify otherwise. If you don't want a new line add a comma:

print "Hello, World!",

Second, you are printing the return of the x() function which is None. The function f() is equivalent to this:

def x():
    print "Hello, World!"
    return None

So print x() prints None.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Thank you! This was dumb of me... I should be returning the "Hello, World!" not printing it. Problem solved =). – chown Nov 27 '11 at 20:25
1
def x():
   print "Hello, World!"

Will execute print and return None - additional newlines are generated by print and None is printed since you wrote print x() :)

If you wish to eliminate the additional newline, write x instead as:

def x():
   sys.stdout.write("Hello, World!")
jsalonen
  • 29,593
  • 15
  • 91
  • 109