62
6. Fruitful functions — How to Think Like a Computer Scientist: Learning with Python 3
http://openbookproject.net/thinkcs/python/english3e/fruitful_functions.html[1/4/2012 9:37:16 PM]
6.3. Debugging with
print
Another powerful technique for debugging (an alternative to single-stepping and inspection of
program variables), is to insert extra
print functions in carefully selected places in your code. Then,
by inspecting the output of the program, you can check whether the algorithm is doing what you
expect it to. Be clear about the following, however:
You must have a clear solution to the problem, and must know what should happen before you
can debug a program. Work on
solving
the problem on a piece of paper (perhaps using a
flowchart to record the steps you take)
before
you concern yourself with writing code. Writing a
program doesn’t solve the problem — it simply
automates
the manual steps you would take. So
first make sure you have a pen-and-paper manual solution that works. Programming then is
about making those manual steps happen automatically.
Do not write chatterbox functions. A chatterbox is a fruitful function that, in addition to its
primary task, also asks the user for input, or prints output, when it would be more useful if it
simply shut up and did its work quietly.
For example, we’ve seen built-in functions like
range,
max and
abs. None of these would be
useful building blocks for other programs if they prompted the user for input, or printed their
results while they performed their tasks.
So a good tip is to avoid calling
print and
input functions inside fruitful functions,
unless the
primary purpose of your function is to perform input and output
. The one exception to this rule
might be to temporarily sprinkle some calls to
print into your code to help debug and
understand what is happening when the code runs, but these will then be removed once you get
things working.
6.4. Composition
As you should expect by now, you can call one function from within another. This ability is called
composition.
As an example, we’ll write a function that takes two points, the center of the circle and a point on the
perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables
xc and
yc, and the perimeter point is in
xp and
yp. The first step is to find the radius of the circle, which is the distance between the two points.
Fortunately, we’ve just written a function,
distance, that does just that, so now all we have to do is
use it:
2
3
4
def distance(x1, y1, x2, y2):
return math.sqrt( (x2-x1)**2 + (y2-y1)**2 )
>>> distance(1, 2, 4, 6)
5.0
1
radius = distance(xc, yc, xp, yp)