Chapter 4. Functions
In the last chapter, we looked at basic procedural statements in Python. Here, we’ll move on to explore a set of additional statements that create functions of our own. In simple terms, functions are a device that groups a bunch of statements, so they can be run more than once in a program. Functions also let us specify parameters, which may differ each time a function’s code is run. Table 4.1 summarizes the function-related statements we’ll study in this chapter.
Table 4-1. Function-Related Statements
|
Statement |
Examples |
|---|---|
|
Calls |
myfunc("spam, ham, toast\n")
|
|
|
def adder(a, b, c=1, *d): return a+b+c+d[0] |
global |
def function(): global x, y; x = 'new' |
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 ...