Chapter 16. 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 16-1 summarizes the primary function-related tools we’ll study in this part of the book.

Table 16-1. Function-related statements and expressions

Statement

Examples

Calls

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

def, 
return

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

global

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

nonlocal

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

yield

def squares(x): ...

Get Learning Python, 4th 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.