繁体   English   中英

Python函数-未定义全局变量

[英]Python function - Global variable not defined

我参加了学习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

您为参数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 与文档字符串相一致; 在这里,它们被命名为make_str_from_rowboard_contains_word_in_row 您的boardcontainswordinrow函数使用 make_str_from_row ,而不是makestrfromrow ,因此您也必须对此进行更正。 一个方向或另一个方向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM