46
108
3 Functions and branching
print line.__doc__
which prints out the documentation of the line function above:
Compute the coefficients a and b in the mathematical
expression for a straight line y = a*x + b that goes
through two points (x0, y0) and (x1, y1).
x0, y0: a point on the line (float objects).
x1, y1: another point on the line (float objects).
return: coefficients a, b for the line (y=a*x+b).
If the function n line is in a file funcs.py, we may also run pydoc
funcs.line ina terminal window tolookthe documentationof the
line function in terms of the function signature and the doc string.
Doc strings often contain interactive sessions, copied from a Python
shell, to illustrate how the function is used. We can add such a session
to the doc string in the line function:
def line(x0, y0, x1, y1):
"""
Compute the coefficients a and b in the mathematical
expression for a straight line y = a*x + b that goes
through two points (x0,y0) and (x1,y1).
x0, y0: a point on the line (float).
x1, y1: another point on the line (float).
return: coefficients a, b (floats) for the line (y=a*x+b).
Example:
>>> a, b = line(1, -1, 4, 3)
>>> a
1.3333333333333333
>>> b
-2.333333333333333
"""
a = (y1 - y0)/float(x1 - x0)
b = y0 - a*x0
return a, b
Aparticularly nice feature is that all such interactive sessions in doc
strings can be automatically run, and new results are compared to the
results found in the doc strings. This makes it possible to use interactive
sessions in doc strings both for exemplifying how the code is used and
for testing that the code works.
Function input and output
It is a convention in Python that function arguments represent the
input data to the function, while the returned objects represent the
output data. We can sketch a general Python function as
def somefunc(i1, i2, i3, io4, io5, i6=value1, io7=value2):
# modify io4, io5, io6; compute o1, o2, o3
return o1, o2, o3, io4, io5, io7