Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 445
def_0101 Avatar asked Mar 02 '15 14:03

def_0101


People also ask

Why is my output printing none?

Because you are printing a function that contains a print() function. The output of printing print() is None. Also, the "return" statements in your function don't add anything to the code. You could just leave them out.

How do I stop Python from printing none?

The function call "print(movie_review(9)) is attempting to print the return value. Without a return statement this defaults to none. It can be fixed by adding a return statement on each conditional statement and removing the print.

Why does my code say none?

If we get to the end of any function and we have not explicitly executed any return statement, Python automatically returns the value None. Some functions exists purely to perform actions rather than to calculate and return a result. Such functions are called procedures.

How do I remove none from print?

The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.


2 Answers

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 >>>  
like image 81
Vivek Sable Avatar answered Oct 21 '22 10:10

Vivek Sable


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() 
like image 20
Avinash Raj Avatar answered Oct 21 '22 10:10

Avinash Raj