Think Python for CS114

Chapter 5 Variables and parameters are local

When you create a variable inside a function, it is local, which means that it only exists inside the function. For example:

def cat_twice(part1, part2):
    cat = part1 + part2
    print_twice(cat)

This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:

>>> line1 = 'Bing tiddle '
>>> line2 = 'tiddle bang.'
>>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.

When cat_twice terminates, the variable cat is destroyed. If we try to print it, we get an exception:

>>> print(cat)
NameError: name 'cat' is not defined

Parameters are also local. For example, outside print_twice, there is no such thing as bruce.

5.1 Stack diagrams

To keep track of which variables can be used where, it is sometimes useful to draw a stack diagram. Like state diagrams, stack diagrams show the value of each variable, but they also show the function each variable belongs to.

Each function is represented by a frame. A frame is a box with the name of a function beside it and the parameters and variables of the function inside it. The stack diagram for the previous example is shown in Figure 5.1.

Stack diagram.

Figure 5.1: Stack diagram.

The frames are arranged in a stack that indicates which function called which, and so on. In this example, print_twice was called by cat_twice, and cat_twice was called by __main__, which is a special name for the topmost frame. When you create a variable outside of any function, it belongs to __main__.

Each parameter refers to the same value as its corresponding argument. So, part1 has the same value as line1, part2 has the same value as line2, and bruce has the same value as cat.

If an error occurs during a function call, Python prints the name of the function, the name of the function that called it, and the name of the function that called that, all the way back to __main__.

For example, if you try to access cat from within print_twice, you get a NameError:

Traceback (innermost last):
  File "test.py", line 13, in __main__
    cat_twice(line1, line2)
  File "test.py", line 5, in cat_twice
    print_twice(cat)
  File "test.py", line 9, in print_twice
    print(cat)
NameError: name 'cat' is not defined

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.

5.2 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.

(Reminder: do not use the type function except while debugging.)

5.3 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.

5.4 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).

5.5 Glossary

function:

A 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 definition:

A statement that creates a new function, specifying its name, parameters, and the statements it contains.

function object:

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

header:

The first line of a function definition.

body:

The sequence of statements inside a function definition.

parameter:

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

function call:

A statement that runs a function. It consists of the function name followed by an argument list in parentheses.

argument:

A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.

local variable:

A variable defined inside a function. A local variable can only be used inside its function.

return value:

The result of a function. If a function call is used as an expression, the return value is the value of the expression.

fruitful function:

A function that returns a value.

void function:

A function that always returns None.

None:

A special value returned by void functions.

module:

A file that contains a collection of related functions and other definitions.

import statement:

A statement that reads a module file and creates a module object.

module object:

A value created by an import statement that provides access to the values defined in a module.

dot notation:

The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.

flow of execution:

The order statements run in.

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.

5.6 Exercises

Exercise 5.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.

Exercise 5.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. 1.

    Type this example into a script and test it.

  2. 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. 3.

    Copy the definition of print_twice from earlier in this chapter to your script.

  4. 4.

    Use the modified version of do_twice to call print_twice twice, passing ’spam’ as an argument.

  5. 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.

Exercise 5.3.

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

  1. 1.

    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('-')

    The output of these statements is ’+ -’ on the same line. The output from the next print statement would begin on the next line.

  2. 2.

    Write a function that draws a similar grid with four rows and four columns.

Credit: This exercise is based on an exercise in Oualline, Practical C Programming, Third Edition, O’Reilly Media, 1997.