Python:函数总是返回无 [英] Python: Function always returns None

查看:55
本文介绍了Python:函数总是返回无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些基本如下所示的 Python 代码:

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

奇怪的是:print(my_list) 打印出正确的内容.但是,打印函数返回值的第二个打印语句总是打印无".即使我用 return("abc") 替换了正常的 return 语句,它仍然是 None.

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.

由于变量的内容似乎在return语句前一行是正确的,我不知道从哪里开始调试.是否有任何常见问题可能导致这种情况?

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?

推荐答案

情况如下:

  1. 您调用 process(my_start_list).
  2. 在函数中,如果len(my_list) > 则执行if块.1,并且那里没有 return 语句.现在,由于 else 还没有被执行,而且因为那是你有 return 子句的唯一地方,你返回默认值 None.
  3. 如果列表中有 0 或 1 个元素,则返回该列表.
  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.

要解决此问题,您需要返回 process(my_list) 返回的列表.

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

即:

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

这篇关于Python:函数总是返回无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆