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.
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)
- But now we might spot that a square is a special kind of rectangle.
- A square simply uses the same value for both the height and the width.
- We already have a function that draws a rectangle, so we can use that to draw our square.
def drawSquare(tx, sz): # a new version of drawSquare
drawRectangle(tx, sz, sz)
Here is the entire example with the necessary set up code.
Reasons to create new functions:
- 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.
- Creating a new function can make a program smaller by eliminating repetitive code.
- Sometimes you can write functions that allow you to solve a specific problem using a more general solution.