Python函数 - 未定义的全局变量

时间:2013-10-05 15:43:45

标签: python

我参加了一门学习Python编程的课程。对于某项任务,我们必须编写下面粘贴的代码。

这部分代码由两个函数组成,第一个是make_str_from_row,第二个是contains_word_in_row。您可能已经注意到第二个函数重用了第一个函数。我已经传递了第一个函数但是我无法传递第二个函数,因为当它必须重用它时会给出第一个函数的错误,这是令人困惑的,因为我的第一个函数没有出现任何错误。它表示未定义全局变量row_index

顺便说一下,第二个函数已在初始化代码中给出,因此它不会出错。我不知道出了什么问题,特别是因为我已经通过了可能必须出错的代码。

我试过要求团队提供一些反馈意见,以防在评分者中出现一些错误,但已经过了一个星期而我没有回复,截止日期是2天。我不是在这里要求答案我只想问某人对给定错误的解释,以便我自己找出解决方案。我非常感谢你的帮助。

def makestrfromrow(board, rowindex):
    """ (list of list of str, int) -> str

    Return the characters from the row of the board with index row_index
    as a single string.

    >>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
    'ANTT'
    """

    string = ''
    for i in board[row_index]:
        string = string + i
    return string

def boardcontainswordinrow(board, word):
    """ (list of list of str, str) -> bool

    Return True if and only if one or more of the rows of the board contains
    word.

    Precondition: board has at least one row and one column, and word is a
    valid word.

    >>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
    True
    """

    for row_index in range(len(board)):
        if word in make_str_from_row(board, row_index):
            return True

    return False

1 个答案:

答案 0 :(得分:4)

您将参数命名为rowindex,但在函数体中使用名称row_index

修复一个或另一个。

演示,修复函数体中使用的名称以匹配参数:

>>> def makestrfromrow(board, rowindex):
...     string = ''
...     for i in board[rowindex]:
...         string = string + i
...     return string
... 
>>> makestrfromrow([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
'ANTT'

请注意,此功能和boardcontainswordinrow 与docstring一致;它们被命名为make_str_from_rowboard_contains_word_in_row。您的boardcontainswordinrow函数使用 make_str_from_row,而不是makestrfromrow,因此您也必须更正;一个方向或另一个方向。

相关问题