Python 为什么在输出中打印“无”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28812851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is this printing 'None' in the output?
提问by def_0101
I have defined a function as follows:
我定义了一个函数如下:
def lyrics():
print "The very first line"
print lyrics()
However why does the output return None
:
但是为什么输出返回None
:
The very first line
None
采纳答案by Vivek Sable
Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.
因为有两个打印语句。第一个是内部功能,第二个是外部功能。当函数不返回任何东西时,它返回 None 值。
Use return
statement at end of function to return value.
return
在函数末尾使用语句返回值。
e.g.:
例如:
Return None value.
返回无值。
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Use return statement
使用返回语句
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
回答by Avinash Raj
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
由于双打印功能。我建议你使用return
而不是print
在函数定义里面。
def lyrics():
return "The very first line"
print(lyrics())
OR
或者
def lyrics():
print("The very first line")
lyrics()