目次
- python interactive mode
- python docstring
Interactivemode
python3 -i [file名]
で呼び出せる。これを使えばファイルの中身を引き継いだ状態でシェルを動かせる。
例えば
test.py
from operator import floordiv, mod
def divide_exact(n, d):
return floordiv(n, d), mod(n, d)
#floordiv(n, d) = n // d, mod(n, d) = n % d
q, r = divide_exact(2013, 10)
print('Quotient:', q)
print('Remainder:', r)
というやり方もあるがinteractive modeを使えば
test2.py
from operator import floordiv, mod
def divide_exact(n, d):
return floordiv(n, d), mod(n, d)
#floordiv(n, d) = n // d, mod(n, d) = n % d
q, r = divide_exact(2013, 10)
をやってからターミナルに戻ってpython3 -i test2.py
>>> q
201
>>> r
3
Docstring
簡単にいえばそれぞれの関数が何をするのかをコメントで書くことを指す。基本的にdef
の真下に書くのが基本。
test2.py
from operator import floordiv, mod
def divide_exact(n, d):
"""return the quotient and remainder of dividing N by D"""
#コメント内ではなぜか引数を大文字にするという習慣があるらしい
return floordiv(n, d), mod(n, d)
q, r = divide_exact(2013, 10)
実際にどんなことが起きるのかを付け足しても構わない。
test2.py
from operator import floordiv, mod
def divide_exact(n, d):
"""return the quotient and remainder of dividing N by D
>>> q, r = divide_exact(2013, 10)
>>> q
201
>>> r
3
"""
return floordiv(n, d), mod(n, d)
またpython3 -m doctest test2.py
でコメントアウトで書いた内容をそのまま動かすことも出来る。python3 -m doctest -v test2.py
で詳細を追うことも可能。
Trying:
q, r = divide_exact(2013, 10)
Expecting nothing
ok
Trying:
q
Expecting:
201
ok
Trying:
r
Expecting:
3
ok
1 items had no tests:
test402
1 items passed all tests:
3 tests in test402.divide_exact
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
エラーの場合はこんな感じ
Trying:
q, r = divide_exact(2013, 10)
Expecting nothing
ok
Trying:
q
Expecting:
201
ok
Trying:
r
Expecting:
2
**********************************************************************
File "test402.py", line 9, in test402.divide_exact
Failed example:
r
Expected:
2
Got:
3
1 items had no tests:
test402
**********************************************************************
1 items had failures:
1 of 3 in test402.divide_exact
3 tests in 2 items.
2 passed and 1 failed.
***Test Failed*** 1 failures.