Skip to content Skip to sidebar Skip to footer

Doctest Of Function To Make A List Of Squares

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,

Solution 1:

Fixing the error

Just add some spaces:

defsquares(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**2for i inrange(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 5of 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, infindself._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.

Post a Comment for "Doctest Of Function To Make A List Of Squares"