textbook 1.5
- def
- while循环
- if elif else
- 自己写程序时候多测试,以后要多多的及时测试自己的代码:
- 断言,语句判断为false时候,提示error,警示后面那句话
assert fib(8) == 13, ‘The 8th Fibonacci number should be 13’ - doctest 提到了一个可以import的测试方法,在函数注释里写上例子,以下代码都是1.5Control里的例子,非原创
- 断言,语句判断为false时候,提示error,警示后面那句话
>>> def sum_naturals(n):
"""Return the sum of the first n natural numbers.
>>> sum_naturals(10)
55
>>> sum_naturals(100)
5050
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total
调用测试模块进行测试
>>> from doctest import testmod
>>> testmod()
TestResults(failed=0, attempted=2)
可以看到更详尽的测试信息,如下:
>>> from doctest import run_docstring_examples
>>> run_docstring_examples(sum_naturals, globals(), True)
Finding tests in NoName
Trying:
sum_naturals(10)
Expecting:
55
ok
Trying:
sum_naturals(100)
Expecting:
5050
ok
非交互式命令行,写在文件里的时候:
python3 -m doctest <python_source_file>