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, return

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 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—one 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—how 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.

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.