Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:递归函数中的返回问题_Python_Recursion - Fatal编程技术网

python:递归函数中的返回问题

python:递归函数中的返回问题,python,recursion,Python,Recursion,出于教育目的,我正在用Python实现一个tic-tac-toe游戏 设置播放器X或O的函数是递归的: def set_marker(player,board): print "\nplayer",player x = y = 3 while(x not in range(0,3)): x = input("x: ") while(y not in range(0,3)): y = input("y: ") if board[

出于教育目的,我正在用Python实现一个tic-tac-toe游戏

设置播放器X或O的函数是递归的:

def set_marker(player,board):
   print "\nplayer",player

   x = y = 3
   while(x not in range(0,3)):
       x = input("x: ")
   while(y not in range(0,3)):    
       y = input("y: ")

   if board[x][y] == 0:
       board[x][y]=player
       return board
   else:
       set_marker(player,board)
       # return board
参数:

board = 2dimensional list ( [[0, 0, 0], [0, 0, 0], [0, 0, 0]] )
player = int (value = '1' or '2')
如果我将“X”设置为已使用的字段,我将再次调用该函数。 当这种情况发生时,我在主循环中再次使用“board”时,脚本抛出以下错误:

Python: TypeError: 'NoneType' object has no attribute '__getitem__'
在这种情况下,电路板的类型为:
none
。 我只需在
else:
部分返回
board
就解决了这个问题

我的问题是:

为什么我还必须在else中返回board,因为我调用函数直到返回正确的board

set_marker(player,board)
应该是:

return set_marker(player,board)
否则,只需递归调用,而不传递结果。假设在第一次迭代中它进入else,它将调用
set\u marker
,然后可能返回
board
,此时外部调用将完成而不返回任何内容,因此出现
TypeError

尽管最好不要使用递归:

def set_marker(player,board):
    print "\nplayer",player

    x = y = 3
    while(x == 3 or board[x][y] != 0):
        while(x not in range(0,3)):
            x = input("x: ")
        while(y not in range(0,3)):    
            y = input("y: ")

        if board[x][y] == 0:
            board[x][y]=player
            return board
应该是:

return set_marker(player,board)
否则,只需递归调用,而不传递结果。假设在第一次迭代中它进入else,它将调用
set\u marker
,然后可能返回
board
,此时外部调用将完成而不返回任何内容,因此出现
TypeError

尽管最好不要使用递归:

def set_marker(player,board):
    print "\nplayer",player

    x = y = 3
    while(x == 3 or board[x][y] != 0):
        while(x not in range(0,3)):
            x = input("x: ")
        while(y not in range(0,3)):    
            y = input("y: ")

        if board[x][y] == 0:
            board[x][y]=player
            return board

我希望使用以下语法:

   else:
       return set_marker(player,board)

当您进行导致if语句第一部分的调用时,它将返回“board”,但该返回值需要通过调用链传播回来。如果不从else块返回递归调用中找到的值,则不会返回任何内容。

我希望使用以下语法:

   else:
       return set_marker(player,board)

当您进行导致if语句第一部分的调用时,它将返回“board”,但该返回值需要通过调用链传播回来。如果不从else块返回递归调用中找到的值,则不会返回任何值。

谢谢,如果我不将其设置为递归函数,请在调用该函数时进行循环,直到我的返回值不再为none,对吗?谢谢,如果我不将其设置为递归函数,你会在调用函数时做一个循环,直到我的返回值不再为none,对吗?