简体   繁体   English

Python-如何获得一个实际上返回“无”的函数?

[英]Python - How to get a function to actually return `None`?

Output for: 输出为:

def test(c):
    if c == 4:
       return None
    return 'test'

returns 'test' given anything I put in such as test(500) but when I try test(4) the function simply skips and pretends I never ran it, but I want it to show None . 给定我输入的任何内容test(500)例如test(500)都返回'test'但是当我尝试test(4)该函数只是跳过并假装我从未运行过它,但我希望它显示None So, 所以,

>> test(500)
'test'
>> test(4)
>>

is what happens. 会发生什么。 My goal is for a None to return without having to use print in the function: 我的目标是None返回,而不必在函数中使用print:

>> test(4)
None

Help! 救命!

It is returning None. 它返回None。 Nothing is printed, because the output shows the result, which is None, which is nothing, so it is not shown. 什么都不会打印,因为输出会显示结果,结果为None(无),什么都没有,因此未显示。

It is returning None . 它返回None If you want to see that this is true without putting print in the method definition, you can do this: 如果您希望在不将print放入方法定义的情况下做到这一点,则可以执行以下操作:

print test(4)
> None

None is the result returned by things that "don't return anything", like list.sort or the Python 3 print function. None是事返回“不返回任何东西”,喜欢的结果list.sort或Python 3的print功能。 If an expression you type at the interactive prompt evaluates to None , Python won't automatically print it, since it thinks you probably called a "doesn't return anything" function, and it would be confusing to have sessions like 如果您在交互式提示符下键入的表达式的计算结果为None ,则Python不会自动打印该表达式,因为它认为您可能调用了“不返回任何内容”功能,因此像

>>> l = [3, 2, 1]
>>> l.sort()
None
>>> print(l)
[1, 2, 3]
None

If you want to print it anyway, you need to explicitly print it. 如果仍要打印,则需要显式print

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM