This list of functions is called a traceback. It tells you what program file the error occurred in, and what line, and what functions were executing at the time. It also shows the line of code that caused the error.

The order of the functions in the traceback is the same as the order of the frames in the stack diagram. The function that is currently running is at the bottom.

3.10 Fruitful functions and void functions

Some of the functions we have used, such as the math functions, return results; for lack of a better name, I call them fruitful functions. Other functions, like print_twice, perform an action but don't return a value. They are called void functions.

When you call a fruitful function, you almost always want to do something with the result; for example, you might assign it to a variable or use it as part of an expression:

x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2

When you call a function in interactive mode, Python displays the result:

>>> math.sqrt(5)
2.2360679774997898

But in a script, if you call a fruitful function all by itself, the return value is lost forever!

math.sqrt(5)

This script computes the square root of 5, but since it doesn't store or display the result, it is not very useful.

Void functions might display something on the screen or have some other effect, but they don't have a return value. If you assign the result to a variable, you get a special value called None.

>>> result = print_twice('Bing')
Bing
Bing
>>> print(result)
None

The value None is not the same as the string 'None'. It is a special value that has its own type:

>>> type(None)
<class 'NoneType'>

The functions we have written so far are all void. We will start writing fruitful functions in a few chapters.

3.11 Why functions?

It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:

  • Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
  • Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
  • Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
  • Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.

3.12 Debugging

One of the most important skills you will acquire is debugging. Although it can be frustrating, debugging is one of the most intellectually rich, challenging, and interesting parts of programming.

In some ways debugging is like detective work. You are confronted with clues and you have to infer the processes and events that led to the results you see.

Debugging is also like an experimental science. Once you have an idea about what is going wrong, you modify your program and try again. If your hypothesis was correct, you can predict the result of the modification, and you take a step closer to a working program. If your hypothesis was wrong, you have to come up with a new one. As Sherlock Holmes pointed out, "When you have eliminated the impossible, whatever remains, however improbable, must be the truth." (A. Conan Doyle, The Sign of Four)

For some people, programming and debugging are the same thing. That is, programming is the process of gradually debugging a program until it does what you want. The idea is that you should start with a working program and make small modifications, debugging them as you go.

For example, Linux is an operating system that contains millions of lines of code, but it started out as a simple program Linus Torvalds used to explore the Intel 80386 chip. According to Larry Greenfield, "One of Linus's earlier projects was a program that would switch between printing AAAA and BBBB. This later evolved to Linux." (The Linux Users' Guide Beta Version 1).

3.13 Glossary

TermDefinition
functionA named sequence of statements that performs some useful operation. Functions may or may not take arguments and may or may not produce a result.
function definitionA statement that creates a new function, specifying its name, parameters, and the statements it contains.
function objectA value created by a function definition. The name of the function is a variable that refers to a function object.
headerThe first line of a function definition.
bodyThe sequence of statements inside a function definition.
parameterA name used inside a function to refer to the value passed as an argument.
function callA statement that runs a function. It consists of the function name followed by an argument list in parentheses.
argumentA value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
local variableA variable defined inside a function. A local variable can only be used inside its function.
return valueThe result of a function. If a function call is used as an expression, the return value is the value of the expression.
fruitful functionA function that returns a value.
void functionA function that always returns None.
NoneA special value returned by void functions.
moduleA file that contains a collection of related functions and other definitions.
import statementA statement that reads a module file and creates a module object.
module objectA value created by an import statement that provides access to the values defined in a module.
dot notationThe syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
compositionUsing an expression as part of a larger expression, or a statement as part of a larger statement.
flow of executionThe order statements run in.
stack diagramA graphical representation of a stack of functions, their variables, and the values they refer to.
frameA box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.
tracebackA list of the functions that are executing, printed when an exception occurs.

3.14 Exercises

Exercise 3.1. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.

>>> right_justify('monty')
                                                                 monty

Hint: Use string concatenation and repetition. Also, Python provides a built-in function called len that returns the length of a string, so the value of len('monty') is 5.

Python Challenge

Exercise 3.1: right_justify

Write a function named right_justify that takes a string s and prints it with enough leading spaces so that the last letter is in column 70.

Python idle

Run the code first so AI Tutor can see the latest output or error.

Hints

Reference Solution

Exercise 3.2. A function object is a value you can assign to a variable or pass as an argument. For example, do_twice is a function that takes a function object as an argument and calls it twice:

def do_twice(f):
    f()
    f()

Here's an example that uses do_twice to call a function named print_spam twice:

def print_spam():
    print('spam')
do_twice(print_spam)
  1. Type this example into a script and test it.
  2. Modify do_twice so that it takes two arguments, a function object and a value, and calls the function twice, passing the value as an argument.
  3. Copy the definition of print_twice from earlier in this chapter to your script.
  4. Use the modified version of do_twice to call print_twice twice, passing 'spam' as an argument.
  5. Define a new function called do_four that takes a function object and a value and calls the function four times, passing the value as a parameter. There should be only two statements in the body of this function, not four.

Solution: https://thinkpython.com/code/do_four.py

Python Challenge

Exercise 3.2: do_twice and do_four

Complete the following tasks:

  1. Implement do_twice(f, value) that calls f(value) twice.
  2. Implement do_four(f, value) that calls f(value) four times using only two statements in its body.
Python idle

Run the code first so AI Tutor can see the latest output or error.

Hints

Reference Solution

Exercise 3.3. Note: This exercise should be done using only the statements and other features we have learned so far.

Write a function that draws a grid like the following:

+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +

Hint: to print more than one value on a line, you can print a comma-separated sequence of values:

print('+', '-')

By default, print advances to the next line, but you can override that behavior and put a space at the end, like this:

print('+', end=' ')
print('-')

Python Challenge

Exercise 3.3: Draw a Grid

Write a function that draws a 2x2 grid using +, -, and | characters.

Python idle

Run the code first so AI Tutor can see the latest output or error.

Hints

Reference Solution