Doctest函数用于制作正方形列表

时间:2014-08-12 02:52:27

标签: python doctest

我正在尝试定义一个函数来返回给定范围内整数的正方形:

#this is my code

def squares(start, end):
    """
    Given the starting and ending numbers,
    return a list of the squares of the numbers from start to end.

    >>>squares(1, 5)
    [1, 4, 9, 16, 25]
    >>>squares(2, 4)
    [4, 9, 16]
    >>>squares(0, 1)
    [0, 1]
    >>>squares(0, 2)
    [0, 1, 4]
    """
    return [i**2 for i in range(start, end+1)]

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE)

这导致了大约30个其他错误,我不知道如何修复它。

    ValueError: line 5 of the docstring for __main__.squares lacks blank after >>>: '>>>squares(1, 5)'

1 个答案:

答案 0 :(得分:1)

修复错误

只需添加一些空格:

def squares(start, end):
    """
    Given the starting and ending numbers,
    return a list of the squares of the numbers from start to end.

    >>> squares(1, 5)
    [1, 4, 9, 16, 25]
    >>> squares(2, 4)
    [4, 9, 16]
    >>> squares(0, 1)
    [0, 1]
    >>> squares(0, 2)
    [0, 1, 4]
    """
    return [i**2 for i in range(start, end+1)]

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE)

如何阅读python stacktrace

阅读python stacktrace可能很棘手。首先,请注意它没有产生“大约30个其他错误”。 Python在第一个错误处停止。在这种情况下,错误是:

ValueError: line 5 of the docstring for __main__.squares lacks blank after >>>: '>>>squares(1, 5)'

它告诉您在>>>和命令squares(1, 5)之间添加空格。

其他令人困惑的行告诉python用于解决该错误的路径。让我们看看前几行:

Traceback (most recent call last):
  File "sq.py", line 20, in <module>
    doctest.testmod(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE)
  File "/usr/lib/python2.7/doctest.py", line 1885, in testmod
    for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
  File "/usr/lib/python2.7/doctest.py", line 900, in find
    self._find(tests, obj, name, module, source_lines, globs, {})

这些行不是单独的错误。他们告诉python如何到达导致错误的行。对于初学者来说,它说python正在执行文件sq.py的第20行调用doctest.testmod。从那里开始,它转到了doctest.py的第1885行,它引用了doctest.py的第900行,依此类推。