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.
Step 1 of 25 line that has just executed next line to execute Code visualized with Online Python Tutor |
| |||||||||||||||||||||||||||||||||||
(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)
- 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.
1
import turtle
2
3
def drawRectangle(t, w, h):
4
"""Get turtle t to draw a rectangle of width w and height h."""
5
for i in range(2):
6
t.forward(w)
7
t.left(90)
8
t.forward(h)
9
t.left(90)
10
11
def drawSquare(tx, sz): # a new version of drawSquare
12
drawRectangle(tx, sz, sz)
13
14
wn = turtle.Screen() # Set up the window
15
16
tess = turtle.Turtle() # create tess
17
18
drawSquare(tess, 50)
19
20
wn.exitonclick()
21
(ch04_3)
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.