Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Function always returns None

Tags:

python

return

I have some Python code that basically looks like this:

my_start_list = ...

def process ( my_list ):
    #do some stuff
    
    if len(my_list) > 1:
        process(my_list)
    else:
        print(my_list)
        return my_list
   
print(process(my_start_list))

The strange thing is: print(my_list) prints out the correct content. However, the second print statement printing the return value of the function always prints None. Even if I replace the normal return statement with return("abc") it is still None.

As the content of the variable seems to be correct one line before the return statement, I don't know where to start debugging. Are there any common problems that may cause this?

like image 421
helm Avatar asked Apr 03 '13 13:04

helm


People also ask

Why is my function returning None in Python?

Functions often print None when we pass the result of calling a function that doesn't return anything to the print() function. All functions that don't explicitly return a value, return None in Python.

Why would a function return None?

00:19 There are basically three ways to cause a value of None to be returned from a function: if the function doesn't have a return statement at all, if you have a return statement with no return value, or you can explicitly return None .

How do I fix None in Python?

Fix input() returning None in Python # The input() function most commonly returns None when passing it a call to the print() function. To get around this, make sure to pass a string to the input() function and not a call to the print() function. Copied!

Can a Python function return nothing?

In Python, it is possible to compose a function without a return statement. Functions like this are called void, and they return None, Python's special object for "nothing".


1 Answers

Here's what happening:

  1. You call process(my_start_list).
  2. In the function, the if block is executed if len(my_list) > 1, and there are no return statement there. Now, since the else has not been executed and since that is the only place where you have the return clause, you return the default which is None.
  3. If you have 0 or 1 elements in your list, you return that list.

To fix this, you'd want to return the list returned by process(my_list).

That is:

def process(my_list):
    # do some stuff
    ...
    if len(my_list) > 1:
        return process(my_list)
    else:
        print(my_list)
        return my_list
like image 80
pradyunsg Avatar answered Oct 26 '22 21:10

pradyunsg