3.1 Functions and Abstraction

Functions are an example of abstraction. They allow us to refer to a block of Python code by name, and execute that code. The function executes the code without knowing what it is, or how it works. In fact, we’ve secretly been doing exactly that already, except we’ve been using the word "command" instead of "function". All of the Processing code for drawing shapes from Chapter 2 are examples of using functions.

Recall from Chapter 1 that algorithms can have input. Thus, it may not surprise you that functions can have input, and indeed most functions do. Function inputs in Python are called arguments. When we used the line function before, we provided four numbers that told the Processing environment where to draw the line on the screen. Those numbers were arguments to the line function.

We also said in Chapter 1 that algorithms could have output. Python functions can have output too, but we’re not going to talk about that too much until a little later. Of course, you might rightly be asking yourself: “isn’t making something appear on the computer’s monitor a form of output?”. In a way, that’s true. However, concerning functions, output has an exact and specific meaning and making something appear on the screen doesn’t qualify. We’ll return to this point in a later chapter.

The key thing to note about functions is that, at the time that you write the code that calls them, you only need to know what the function does, not how it does it. You might think that drawing a line on a screen sounds pretty simple, but it’s still too abstract for a computer to be able to do it without further explanation. The authors of Processing wrote the details of the line function for us, and we don’t need to know how they did it to use it. All we need to know is what it does, and what the meaning of its arguments are.