簡體   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