我已经定义了一个函数如下:
def lyrics():
print "The very first line"
print lyrics()
Run Code Online (Sandbox Code Playgroud)
但是为什么输出会返回None:
The very first line
None
Run Code Online (Sandbox Code Playgroud)
Viv*_*ble 32
因为有两个打印语句.第一个是内部功能,第二个是外部功能.当函数没有返回任何时候它返回无值.
return在函数末尾使用语句返回值.
例如:
返回无值.
>>> def test1():
... print "In function."
...
>>> a = test1()
In function.
>>> print a
None
>>>
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>>
Run Code Online (Sandbox Code Playgroud)
使用return语句
>>> def test():
... return "ACV"
...
>>> print test()
ACV
>>>
>>> a = test()
>>> print a
ACV
>>>
Run Code Online (Sandbox Code Playgroud)
由于双重打印功能.我建议你使用return而不是print在函数定义中.
def lyrics():
return "The very first line"
print lyrics()
Run Code Online (Sandbox Code Playgroud)
要么
def lyrics():
print "The very first line"
lyrics()
Run Code Online (Sandbox Code Playgroud)