"""
doctest_example.py
This shows
(1) python documentation strings, and
(2) a test of a function within such a string.
Here the function is trivial : it simply doubles its argument.
The whole program is also trivial: it asks for a number,
and then prints what double() does to it.
The doc strings are the text within the triple quotes.
They're stored within <thing>.__doc__ and will be printed
if you ask for help(<thing>) in an interactive python session.
The tests are exactly what you would see by running an
interactive python session and evaluating the function.
Jim Mahoney | Sep 2012
"""
def double(x):
""" Return 2*x
>>> double(3)
6.1
>>> double('a')
'aa'
"""
return 2*x
def main():
number = input("What is the number? ")
print "Twice " + str(number) + " is " + str(double(number))
def _test():
""" Run the tests in this file,
i.e. the doc string parts with with ">>> ... " as if at a python prompt.
Google 'python doctest' for the details.
Usage:
$ python <filename> # 1. Invoke python on a file as usual.
$ # No warnings means success.
$ python <filename> -v # 2. Invoke with -v (verbose) flag
Trying: # to see details.
double(3)
Expecting:
6
ok
...
"""
import doctest
doctest.testmod() # test a module
# (By default, this module, e.g. this file.)
_test() # run tests
main() # run the main program
syntax highlighted by Code2HTML, v. 0.93pm6