繁体   English   中英

Python递归函数返回Nonetype

[英]Python recursive function returning Nonetype

我有一个函数,它通过2D矩阵递归搜索以找到0值并返回其位置。 这是代码:

    def findNextZero(x, y, board):
       if board[x][y] == 0:
          return (x, y)
       else:
           if y == (SIZE-1):
              # if its at the edge of the "board", the 2d matrix
              findNextZero(x+1, 0, board)
           else:
              findNextZero(x, y+1, board)

当我打印(x,y)时,该函数将打印正确的元组。 但是,如果我尝试返回它,则说返回值是None。 为什么会这样呢?

您将忽略递归调用的返回值。 添加以下内容的return语句:

def findNextZero(x, y, board):
    if board[x][y] == 0:
        return (x, y)
    else:
        if y == (SIZE-1):
            # if its at the edge of the "board", the 2d matrix
            return findNextZero(x+1, 0, board)
        else:
            return findNextZero(x, y+1, board)

如果没有这些return ,则findNextZero()函数将在不显式返回任何内容的情况下结束,从而findNextZero()返回默认的返回值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM