Python 名称错误:未定义str索引

Python 名称错误:未定义str索引,python,Python,当我评估它时,它显示了 NameError:未定义名称“str_index” 我想我已经定义了str索引。您正在make\u move函数中使用str\u索引。该变量不存在于函数的作用域中 def get_position (row_index,col_index,size): """ (int,int,int) -> int Precondition:size >=col_index and size >= row_index Return the

当我评估它时,它显示了

NameError:未定义名称“str_index”

我想我已经定义了str索引。

您正在make\u move函数中使用str\u索引。该变量不存在于函数的作用域中

def get_position (row_index,col_index,size):
    """ (int,int,int) -> int

    Precondition:size >=col_index and size >= row_index

    Return the str_index of the cell with row_index,col_index and size
    >>>get_position (2,2,4)
    5
    >>>get_position (3,4,5)
    13
    """
    str_index = (row_index - 1) * size + col_index - 1  
    return str_index


def make_move( symbol,row_index,col_index,game_board):
    """(str,int,int,str) -> str

    Return the resultant game board with symbol,row_index,col_index and game_board
    >>>make_move("o",1,1,"----")
    "o---"
    >>>make_move("x",2,3,"---------")
    "-----x---"
    """
    length=len(game_board)

    return "-"*(str_index-1)+symbol+"-"*(length-str_index)

尝试将代码更改为:

def make_move(symbol,row_index,col_index,game_board):
    """(str,int,int,str) -> str

    Return the resultant game board with symbol,row_index,col_index and game_board
    >>>make_move("o",1,1,"----")
    "o---"
    >>>make_move("x",2,3,"---------")
    "-----x---"
    """
    length=len(game_board)
    # I am assuming length is the size for get_position
    str_index = get_position(row_index, col_index, length)

    return "-"*(str_index-1)+symbol+"-"*(length-str_index)
以及:

注意:您需要向函数中添加一个大小参数或进行计算

return (row_index - 1) *size + col_index - 1
 str_index =get_position(row_index, col_index, size)
 return "-"*(str_index-1)+symbol+"-"*(length-str_index)