Why is this printing 'None' in the output?

PythonNonetype

Python Problem Overview


I have defined a function as follows:

def lyrics():
    print "The very first line"
print lyrics()

However why does the output return None:

The very first line
None

Python Solutions


Solution 1 - Python

Because there are two print statements. First is inside function and second is outside function. When a function doesn't return anything, it implicitly returns None.

Use return statement at end of function to return value.

e.g.:

Return None.

>>> 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
>>> 

Solution 2 - Python

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondef_0101View Question on Stackoverflow
Solution 1 - PythonVivek SableView Answer on Stackoverflow
Solution 2 - PythonAvinash RajView Answer on Stackoverflow