为什么打印函数返回 None? [英] Why does the print function return None?

查看:64
本文介绍了为什么打印函数返回 None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么外部 print 返回 None.

<预><代码>>>>a = 打印(打印(Python"))Python没有任何>>>打印(类型(a))

我注意到:

<预><代码>>>>a = 打印(嘿")嘿>>>类型(一)

谁能解释一下这里发生的一般情况?谢谢!

解决方案

print() 函数返回 None.您正在打印该返回值.

那是因为print()没有什么返回;它的工作是在将参数转换为字符串后将参数写入文件对象(默认为 sys.stdout).但是 Python 中的所有表达式(包括调用)都会产生一个值,因此在这种情况下会产生 None.

您似乎将打印与返回此处混淆了.Python 交互式解释器打印;它打印直接在提示中运行的表达式的结果,前提是它们不产生 None:

<预><代码>>>>没有任何>>>'一些价值''一些价值'

该字符串已回显(打印)到您的终端,而 None 则没有.

由于 print() 返回 None 但写入相同的输出(您的终端),结果可能看起来相同,但它们是非常不同的动作.我可以让 print() 写入别的东西,而你在终端上看不到任何东西:

<预><代码>>>>从 io 导入 StringIO>>>输出 = StringIO()>>>打印('你好世界!',文件=输出)>>>输出.getvalue()'世界你好!\n'

print() 函数调用没有在终端上产生输出,并返回 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!

解决方案

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.

这篇关于为什么打印函数返回 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆