Functions can Call Other FunctionsΒΆ

The process of breaking a problem into smaller subproblems is called functional decomposition.

Here’s a simple example of functional decomposition using two functions.

(sumofsquares)

Now we will look at another example that uses two functions.

This example illustrates an important computer science problem solving technique called generalization. - Assume we want to write a function to draw a square. - The generalization step is to realize that a square is just a special kind of rectangle.

To draw a rectangle we need to be able to call a function with different arguments for width and height.

def drawRectangle(t, w, h):
    """Get turtle t to draw a rectangle of width w and height h."""
    for i in range(2):
        t.forward(w)
        t.left(90)
        t.forward(h)
        t.left(90)
def drawSquare(tx, sz):        # a new version of drawSquare
    drawRectangle(tx, sz, sz)

Here is the entire example with the necessary set up code.




(ch04_3)

Reasons to create new functions:

  1. Creating a new function gives you an opportunity to name a group of statements. Functions can simplify a program by hiding a complex computation behind a single command. The function (including its name) can capture your mental chunking, or abstraction, of the problem.
  2. Creating a new function can make a program smaller by eliminating repetitive code.
  3. Sometimes you can write functions that allow you to solve a specific problem using a more general solution.
Next Section - Composition