Why does the print function return None?

I’m trying to understand why the outer print returns None.

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

I noticed:

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

Can anyone explain what goes on here generally? Thanks!

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

The function print comes from C language that choose “by design” uses “0” (zero) to indicates success after an script execution. Furthermore all the projects based on this concept like linux, the shell and the python language uses this to inform to the “caller” of a method if was successfully executed or not.

The most commom error at internet is the code 404 – Not found. RFC 2616

For more reference click here


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x