2018-09-17

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裏的例子,非原創
>>> 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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章