Discuss / Python / 自己写的有问题……

自己写的有问题……

Topic source
def fact(n):
    '''
    Simple factorial function with doctest.

    >>> fact(0)
    Traceback (most recent call last):
        ...
    ValueError: 'n' is not positive
    >>> fact(1)
    1
    >>> fact(5)
    120

    '''
    if n<1:
        raise ValueError()
    if n==1:
        return 1
    return n*fact(n-1)
if __name__=='__main__':
    import doctest
    doctest.testmod()

为什么我运行后会出现

E:\python3Code>python others.py
**********************************************************************
File "others.py", line 9, in __main__.fact
Failed example:
    fact(0)
Expected:
    Traceback (most recent call last):
            ...
    ValueError: 'n' is not positive
Got:
    Traceback (most recent call last):
      File "E:\Software\python3\lib\doctest.py", line 1318, in __run
        compileflags, 1), test.globs)
      File "<doctest __main__.fact[0]>", line 1, in <module>
        fact(0)
      File "others.py", line 20, in fact
        raise ValueError()
    ValueError
**********************************************************************
1 items had failures:
   1 of   3 in __main__.fact
***Test Failed*** 1 failures.

但是测试了米粽粽和野子的代码就没这问题 就是要么改

    if n<1:
        raise ValueError()

要么改

    Traceback (most recent call last):
        ...
    ValueError: 'n' is not positive

不理解这是什么状况……

你这里写了提示信息:

>>> fact(0)
Traceback (most recent call last):
    ...
ValueError: 'n' is not positive

那么

if n<1:
    raise ValueError()
  里面也要写

  • 1

Reply