Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata