5.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 procedures 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:

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.

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 to actually accomplish that task.

However, this new program doesn’t work yet. Try running it if you have not already. You will get an error message that “‘square’ is not defined on line 5”. Python has no idea what is meant by square. Before we can run this code, we need to define how the square procedure works.

You have attempted of activities on this page