Chapter 12. Function Basics

In Part III, 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, a function is a device that groups a set of statements, so they can be run more than once in a program. Functions also let us specify parameters that serve as function inputs, and may differ each time a function’s code is run. Table 12-1 summarizes the primary function-related tools we’ll study in this part of the book.

Table 12-1. Function-related statements and expressions

Statement

Examples

Calls

myfunc("spam", ham, "toast")

def, return, yield

def adder(a, b=1, *c): return a+b+c[0]

global

def function( ): global x; x = 'new'

lambda

funcs = [lambda x: x**2, lambda x: x*3]

Why Use Functions?

Before going 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, where they may have been called subroutines or procedures. 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 until now, all the code we’ve been writing runs immediately; functions allow us to group and generalize code to be used arbitrarily many times later.

Procedural ...

Get Learning Python, 2nd Edition 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.