Python 局部变量'';分配前参考
我有一个小问题,关于我的方法中的一个错误(比如在一个类中),我目前正在研究一个人工智能,希望找出机器人可以做的最好的移动,但是当我想返回bestMove时,它会告诉我错误Python 局部变量'';分配前参考,python,python-3.x,Python,Python 3.x,我有一个小问题,关于我的方法中的一个错误(比如在一个类中),我目前正在研究一个人工智能,希望找出机器人可以做的最好的移动,但是当我想返回bestMove时,它会告诉我错误 def computerMove(self, tile, newBoard, legalMoves, isOnCorner): legitMoves = self.getLegalMoves(self.board, tile) for x, y in legitMoves:
def computerMove(self, tile, newBoard, legalMoves, isOnCorner):
legitMoves = self.getLegalMoves(self.board, tile)
for x, y in legitMoves:
if self.isOnCorner(x, y):
return [x, y]
highestPoints = -1
for x, y in legitMoves:
computerBoard = self.getComputerBoard(self.newBoard)
makeYourMove(computerBoard, tile, x, y)
points = countPoints(computerBoard)[tile]
if points > highestPoints:
highestPoints = points
bestMove = [x][y]
return bestMove
但错误表明
UnboundLocalError:赋值前引用的局部变量“bestMove”
请看这段代码:
for x, y in legitMoves:
computerBoard = self.getComputerBoard(self.newBoard)
makeYourMove(computerBoard, tile, x, y)
points = countPoints(computerBoard)[tile]
if points > highestPoints:
highestPoints = points
bestMove = [x][y]
return bestMove
如果没有legitMoves
或没有移动得分points>highestPoints
(我假设情况永远不会是这样,因为countPoints
最有可能返回至少0
),那么将永远不会定义bestMove
,而且bestMove=[x][y]
应该是bestMove=[x,y]
尝试将
bestMove=None
置于for
循环之前,然后在调用代码中处理None
。您必须在for循环之前分配bestMove
一个值,因为如果if条件为false,bestMove
未分配任何值,函数将返回None
。检查我的更新@我很理解你的意思,但它不起作用。检查我的更新!哦,我想我正在解决它,如果我需要更多的帮助,我会回来的!ty@PythonGirl请仔细查看完整的回溯,并尝试阅读其中的所有信息。如果这没有帮助,你可以在这里发布完整的回溯,或者在新问题中发布更好的回溯。事实上,您没有在这里包含回溯,这表明您认为它不相关,而实际上它是有关错误的最相关信息。