Why does the print function return None?

Question:

Why does the outer print in this code display None?

>>> a = print(print("Python"))
Python
None
>>> print(type(a))
<class 'NoneType'>

Why does a become None here, even though hey is printed (rather than None)?

>>> a = print("hey")
hey
>>> type(a)
<class 'NoneType'>

See also: What is the purpose of the return statement? How is it different from printing?

Asked By: user4447887

||

Answers:

The print() function returns None. You are printing that return value.

That’s because print() has nothing to return; its job is to write the arguments, after converting them to strings, to a file object (which defaults to sys.stdout). But all expressions in Python (including calls) produce a value, so in such cases None is produced.

You appear to confuse printing with returning here. The Python interactive interpreter also prints; it prints the result of expressions run directly in on the prompt, provided they don’t produce None:

>>> None
>>> 'some value'
'some value'

The string was echoed (printed) to your terminal, while None was not.

Since print() returns None but writes to the same output (your terminal), the results may look the same, but they are very different actions. I can make print() write to something else, and you won’t see anything on the terminal:

>>> from io import StringIO
>>> output = StringIO()
>>> print('Hello world!', file=output)
>>> output.getvalue()
'Hello world!n'

The print() function call did not produce output on the terminal, and returned None which then was not echoed.

Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.