Chapter 3. Functions

In the previous chapter we used several functions provided by Python, like int and float, and a few provided by the math module, like sqrt and pow. In this chapter, you will learn how to create your own functions and run them. And we’ll see how one function can call another. As examples, we’ll display lyrics from Monty Python songs. These silly examples demonstrate an important feature—the ability to write your own functions is the foundation of programming.

This chapter also introduces a new statement, the for loop, which is used to repeat a computation.

Calling Functions

Once you have defined a function, you can use it inside another function. To demonstrate, we’ll write functions that print the lyrics of “The Spam Song”:

Spam, Spam, Spam, Spam,
Spam, Spam, Spam, Spam,
Spam, Spam,
(Lovely Spam, Wonderful Spam!)
Spam, Spam,

We’ll start with the following function, which takes two parameters:

def repeat(word, n):
    print(word * n)
       

We can use this function to print the first line of the song, like this:

spam = 'Spam, '
repeat(spam, 4)
       
Spam, Spam, Spam, Spam, 
       

To display the first two lines, we can define a new function that uses repeat:

def first_two_lines():
    repeat(spam, 4)
    repeat(spam, 4)
        

And then call it like this:

first_two_lines()
        
Spam, Spam, Spam, Spam, 
Spam, Spam, Spam, Spam, 
        

To display the last three lines, we can define another function, which also uses repeat:

def last_three_lines():
    repeat(spam, 2)
    print('(Lovely Spam, Wonderful Spam!)')
    repeat(spam, 2)
        
last_three_lines()
        
Spam, Spam, 
(Lovely Spam, Wonderful Spam!)
Spam, Spam, 
        

Finally, we can bring it all together with one function that prints the whole verse:

def print_verse():
    first_two_lines()
    last_three_lines()
        
print_verse()
        
Spam, Spam, Spam, Spam, 
Spam, Spam, Spam, Spam, 
Spam, Spam, 
(Lovely Spam, Wonderful Spam!)
Spam, Spam, 
        

When we run print_verse, it calls first_two_lines, which calls repeat, which calls print. That’s a lot of functions.

Of course, we could have done the same thing with fewer functions, but the point of this example is to show how functions can work together.

Repetition

If we want to display more than one verse, we can use a for statement. Here’s a simple example:

for i in range(2):
    print(i)
        
0
1
        

The first line is a header that ends with a colon. The second line is the body, which has to be indented.

The first line starts with the keyword for, a new variable named i, and another keyword, in. It uses the range function to create a sequence of two values, which are 0 and 1. In Python, when we start counting, we usually start from 0.

When the for statement runs, it assigns the first value from range to i and then runs the print function in the body, which displays 0.

When it gets to the end of the body, it loops back around to the header, which is why this statement is called a loop. The second time through the loop, it assigns the next value from range to i, and displays it. Then, because that’s the last value from range, the loop ends.

Here’s how we can use a for loop to print two verses of the song:

for i in range(2):
    print("Verse", i)
    print_verse()
    print()
        
Verse 0
Spam, Spam, Spam, Spam, 
Spam, Spam, Spam, Spam, 
Spam, Spam, 
(Lovely Spam, Wonderful Spam!)
Spam, Spam, 

Verse 1
Spam, Spam, Spam, Spam, 
Spam, Spam, Spam, Spam, 
Spam, Spam, 
(Lovely Spam, Wonderful Spam!)
Spam, Spam, 
        

You can put a for loop inside a function. For example, print_n_verses takes a parameter named n, which has to be an integer, and displays the given number of verses:

def print_n_verses(n):
    for i in range(n):
        print_verse()
        print()
        

In this example, we don’t use i in the body of the loop, but there has to be a variable name in the header anyway.

Glossary

function definition: A statement that creates a function.

header: The first line of a function definition.

body: The sequence of statements inside a function definition.

function object: A value created by a function definition. The name of the function is a variable that refers to a function object.

parameter: A name used inside a function to refer to the value passed as an argument.

loop: A statement that runs one or more statements, often repeatedly.

local variable: A variable defined inside a function, which can only be accessed inside the function.

stack diagram: A graphical representation of a stack of functions, their variables, and the values they refer to.

frame: A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.

traceback: A list of the functions that are executing, printed when an exception occurs.

Exercises

Exercise

Write a function called triangle that takes a string and an integer and draws a triangle with the given height, made up of copies of the string. Here’s an example of a triangle with five levels using the string 'L':

triangle('L', 5)
        
L
LL
LLL
LLLL
LLLLL
        

Exercise

Write a function called rectangle that takes a string and two integers and draws a rectangle with the given width and height, made up of copies of the string. Here’s an example of a rectangle with width 5 and height 4, using the string 'H':

rectangle('H', 5, 4)
        
HHHHH
HHHHH
HHHHH
HHHHH