Composition
One of the most useful features of programming languages is their ability to call one function from within another. This ability is called composition. For example, the argument of a function can be any kind of expression, including arithmetic operators, functions.
>>>math.sqrt(4*4)4.0>>>math.sqrt(math.sqrt(16))2.0
Example:
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.
def distance(x1, y1, x2, y2):dx = x2 - x1dy = y2 - y1dsquared = dx**2 + dy**2result = math.sqrt(dsquared)return resultradius = distance(xc, yc, xp, yp)
The next step is to find the area of a circle with that radius
def area(radius):a = math.pi * radius**2return aresult = area(radius)
Encapsulating these steps in a function, we get:
def circle_area(xc, yc, xp, yp):radius = distance(xc, yc, xp, yp)result = area(radius)return result
The temporary variables radius and result are useful for development and debugging, but once the program is working, we can make it more concise by composing the function calls.
def circle_area(xc, yc, xp, yp):return area(distance(xc, yc, xp, yp))
References
- Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
- Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
- John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
- Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
- Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
- Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
- Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.