Why is this printing ‘None’ in the output? [duplicate]

Posted on

Solving problem is about exposing yourself to as many situations as possible like Why is this printing ‘None’ in the output? [duplicate] and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Why is this printing ‘None’ in the output? [duplicate], which can be followed any time. Take easy to follow this discuss.

Why is this printing ‘None’ in the output? [duplicate]

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
Asked By: def_0101

||

Answer #1:

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.

Use return statement at end of function to return value.

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
>>> 
Answered By: Vivek Sable

Answer #2:

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()
Answered By: Avinash Raj
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.