Skip to main content

Section 17.2 Defining Procedures - Why

How does Python know what to do when we call functions like abs or procedures like alex.forward(50)? Someone had to define them. Defining a new procedure or function associates a name with a name with a sequence of steps.
Why do we make new procedures or functions? There are two primary reasons:
  • Code reuse - A golden rule in programming is DRY - don’t repeat yourself. If you find yourself typing the same code over and over (or by copying and pasting), there is probably a better way to solve the problem. By defining a function or procedure, we can easily reuse a sequence of instructions without typing the entire sequence over and over again.
  • Forming abstractions - By defining a function or procedure, we can hide the messy details of solving a particular problem. We can then use the function or procedure to do the job without stopping to worry about all of the details. If someone else defined the function, we may not even know how all of the details work. But we can still use the function to do a job. The function is an abstraction - something that allows us to think about our problem at a higher level and get more done with each line of code we write.
Examine the program below. Can you easily tell what it does? Click Run and see what happens.
It is not easy to glance at that program and easily tell that it will draw three squares in a row. We could make it easier to understand by adding some comments, and some blank lines to break it into logical sections, but it would still not be fun to read. It also represents a lot of typing.
Now compare that program to this one.
from turtle import *
yessenia = Turtle()

square(yessenia)            # draws a square with yessenia
yessenia.forward(20)

square(yessenia)            # draws a square with yessenia
yessenia.forward(20)

square(yessenia)            # draws a square with yessenia
yessenia.forward(20)
It is much easier to read this program and quickly understand what it is doing. It requires less typing (or copy/pasting) to make this program. And, you could modify this program to draw a fourth square without even understanding how the squares are drawn - square is an abstraction that lets you draw a square without worrying about how that task is accomplished.
You have attempted of activities on this page.