Doctest of function to make a list of squares

天大地大妈咪最大 提交于 2019-12-12 01:58:55

问题


I am trying to define a function to return squares for integers within a given range:

#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)

This is causing about 30 other errors and I dont know how to fix it.

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

回答1:


Fixing the error

Just add some spaces:

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)

How to read a python stacktrace

Reading a python stacktrace can be tricky. First, note that it did not generate "about 30 other errors." Python stops at the first error. In this case, the error is:

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

It tells you to add a space between >>> and the command squares(1, 5).

The rest of the confusing lines tell the path that python took to get to that error. Lets look at the first few lines:

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, {})

These lines are not separate errors. They tell how python reached the line that gave the error. For starters, it says that python was executing line 20 of your file sq.py which called doctest.testmod. From there, it went to line 1885 of doctest.py which called line 900 of doctest.py and so on.



来源:https://stackoverflow.com/questions/25255435/doctest-of-function-to-make-a-list-of-squares

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!