Skip to Content
Learning Python, 3rd Edition
book

Learning Python, 3rd Edition

by Mark Lutz
October 2007
Beginner
752 pages
19h 44m
English
O'Reilly Media, Inc.
Content preview from Learning Python, 3rd Edition

Chapter 15. 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 we can use to 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 can compute a result value and let us specify parameters that serve as function inputs, which may differ each time the code is run. Coding an operation as a function makes it a generally useful tool, which we can use in a variety of contexts.

More fundamentally, functions are the alternative to programming by cutting and pasting—rather than having multiple redundant copies of an operation’s code, we can factor it into a single function. In so doing, we reduce our future work radically: if the operation must be changed later, we only have one copy to update, not many.

Functions are the most basic program structure Python provides for maximizing code reuse and minimizing code redundancy. As we’ll see, functions are also a design tool that lets us split complex systems into manageable parts. Table 15-1 summarizes the primary function-related tools we’ll study in this part of the book.

Table 15-1. Function-related statements and expressions

Statement

Examples

Calls

myfunc("spam", "eggs", meat=ham)

def, return, yield

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

global

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

lambda

Funcs = [lambda x: x**2, lambda x: x*3] ...
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, 6th Edition

Learning Python, 6th Edition

Mark Lutz
Learning Python, 2nd Edition

Learning Python, 2nd Edition

Mark Lutz, David Ascher

Publisher Resources

ISBN: 9780596513986Purchase bookSupplemental ContentErrata Page