def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
<do stuff>
if __name__ == "__main__":
import doctest
doctest.testmod()
编写一个真实的单元测试,并从命令行运行它。我发现这是采用单元测试的最有说服力的原因之一:不管怎样,你都需要在编写方法的同时尝试它们,你也可以用一种此后永远都可以运行的形式来完成它。在
你应该看看Doctests。学习测试是一种非常简单的方法。 基本上,您可以在交互式解释器中编写测试,然后可以将它们复制/粘贴到函数的docstring中。 示例(来自Python文档)
tldr; 在要测试的代码行前面加上“>>>;”,并在其下一行上显示预期结果。还有更多的事情要做,但这应该足够让你开始了。在
您必须引用使用
reload
的pythonshell[x]进行测试。在这种情况下,reload
就可以了-我不必担心它。您还可以:以及以后:
^{pr2}$[x]不要只使用普通shell(在命令行上运行
python
),而应该尝试像IPython或Spyder这样的工具。在相关问题 更多 >
编程相关推荐