Python: Function always returns None

前端 未结 4 764
迷失自我
迷失自我 2020-11-29 11:36

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:
                


        
4条回答
  •  时光取名叫无心
    2020-11-29 12:02

    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
    

提交回复
热议问题