Search code examples
python-3.xpython-moduledoctest

Doctest keeps putting in odd amount of whitespace?


I'm trying to put in doctests in the functions i'm defining like my professor wanted the class to, but it keeps failing on correct outputs on account of whitespace sort of being materialized out of nowhere, how would I combat this?

here's my code:

import math
def circle_area(radius):
    ''' >>> circle_area(5)
    78.54
    '''
    area = round(math.pi*(radius**2),2)
    if radius < 1 or radius > 1000:
        print('ERROR')
        return 0
    else:
        return area

output:

**********************************************************************
File "math_funcs.py", line 46, in __main__.circle_area
Failed example:
    circle_area(5)
Expected:
       78.54
Got:
    78.54
**********************************************************************
1 items had failures:
   1 of   1 in __main__.circle_area
***Test Failed*** 1 failures

Solution

  • >>> circle_area(5) needs to be put on its own line, with the same indentation as the first line of the doctring. That is, instead of this:

        ''' >>> circle_area(5)
        78.54
        '''
    

    do this:

        '''
        >>> circle_area(5)
        78.54
        '''
    

    ETA: Here is the exact working test file that I used:

    #!/usr/bin/env python3
    import math
    def circle_area(radius):
        '''
        >>> circle_area(5)
        78.54
        '''
        area = round(math.pi*(radius**2),2)
        if radius < 1 or radius > 1000:
            print('ERROR')
            return 0
        else:
            return area
    
    import doctest
    doctest.testmod()