A function is a small program that often—but not always—returns a value to the code that invoked the function. You can use functions to organize a program by breaking the program up into small functional units. These small functional units (each one a function!) can be reused to perform the same task over and over again without having to rewrite the code in the function each time. Therefore, the best-written functions tend to be somewhat general in flavor (so that they can be reused).
You’ve already seen a number of examples in Learn How to Program of programs that use functions. For instance, the Rock, Scissors, and Paper program in Chapter 3, “ Using Conditional Statements,” is implemented using a number of functions to help organize the code. For example, in that program, the whoWon function works as a general mechanism for determining if the human player or the computer player won a particular round. Two variables are passed as input to the whoWon function. The variables represent “plays” of the game: iplay, the computer’s move, and uplay, the human’s move. The function returns a value, namely a text message stating whether the computer or the human is the winner of the round of Rocks, Scissors, and Paper.
In Chapter 3, in the Rock, Scissors, and Paper program, I used functions to organize the program because it was the right thing to do—and because it seemed intuitive as to how they worked. This chapter looks at functions in greater depth. It’s an important topic because most wellwritten programs are largely made up of functions.
You may have noticed that I’ve used the word method earlier in this book to refer to something that pretty much seems like a function. So, how are functions and methods different? The truth is that they’re more or less the same thing except that a method is related to an object, and this isn’t necessarily the case for a function. Moreover, internally a method is implemented (meaning “made to work”) using a function. Put another way, the word method is object-speak for a function, and if a function is associated with an object (“encapsulated by the object”), then it’s called a method. I show you how to work with objects in detail in Chapter 7, “ Working with Objects.”
To start with, I show you how to construct your own functions. This is fun and useful material.
Next, you’ll learn how to use the array of arguments associated with a function. Finally, I show you how to use a recursive function, which is a function that calls itself. The recursive function will be used to display the Fibonacci series of numbers, a series that comes up in nature, architecture, and many other contexts.
Functions and methods are pretty much the same things. Technically, a method is a function associated with an object. For more on the distinction, or lack thereof, between functions and methods, see “ Differentiating Between Functions, Methods, and Subroutines.”