© Joey Bernard 2016

Joey Bernard, Python Recipes Handbook, 10.1007/978-1-4842-0241-8_6

6. Functions

Joey Bernard

(1)Fredericton, New Brunswick, Canada

Any modern programming language needs to have some way of combining functionality into reusable chunks of code. In Python, one of the most basic units of reusable code is the function. In this chapter, you will look at how functions work within Python, as well as some places where they may do something surprising.

6-1. Creating Basic Functions


You want to create a basic function to handle a simple task, such as finding the square of two.


Within Python, you can use the built-in def keyword to create a new function.

How It Works

Listing 6-1 shows an example.

Listing 6-1. Defining a Basic Function ...

Get Python Recipes Handbook: A Problem-Solution Approach now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.