I l@ve RuBoard Previous Section Next Section

4.1 Why Use Functions?

Before we get into the details, let's get a clear picture of what functions are about. Functions are a nearly universal program-structuring device. Most of you have probably come across them before in other languages, but as a brief introduction, functions serve two primary development roles:

Code reuse

As in most programming languages, Python functions are the simplest way to package logic you may wish to use in more than one place and more than one time. Up to now, all the code we've been writing runs immediately; functions allow us to group and parametize chunks of code to be used arbitrarily many times later.

Procedural decomposition

Functions also provide a tool for splitting systems into pieces that have a well-defined role. For instance, to make a pizza from scratch, you would start by mixing the dough, rolling it out, adding toppings, baking, and so on. If you were programming a pizza-making robot, functions would help you divide the overall "make pizza" task into chunks梠ne function for each subtask in the process. It's easier to implement the smaller tasks in isolation than it is to implement the entire process at once. In general, functions are about procedure梙ow to do something, rather than what you're doing it to. We'll see why this distinction matters in Chapter 6.

Here, we talk about function basics, scope rules and argument passing, and a handful of related concepts. As we'll see, functions don't imply much new syntax, but they do lead us to some bigger programming ideas.

I l@ve RuBoard Previous Section Next Section