When you create a variable inside a function, it is local, which means that it only exists inside the function. For example:
This function takes two arguments, concatenates them, and prints the result twice. Here is an example that uses it:
When cat_twice
terminates, the variable cat
is destroyed. If we try to print it, we get an exception:
Parameters are also local.
For example, outside print_twice
, there is no
such thing as bruce.
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.
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:
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.
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:
When you call a function in interactive mode, Python displays the result:
But in a script, if you call a fruitful function all by itself, the return value is lost forever!
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.
The value None is not the same as the string ’None’
.
It is a special value that has its own type:
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.)
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.
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).
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.
A statement that creates a new function, specifying its name, parameters, and the statements it contains.
A value created by a function definition. The name of the function is a variable that refers to a function object.
The first line of a function definition.
The sequence of statements inside a function definition.
A name used inside a function to refer to the value passed as an argument.
A statement that runs a function. It consists of the function name followed by an argument list in parentheses.
A value provided to a function when the function is called. This value is assigned to the corresponding parameter in the function.
A variable defined inside a function. A local variable can only be used inside its function.
The result of a function. If a function call is used as an expression, the return value is the value of the expression.
A function that returns a value.
A function that always returns None.
A special value returned by void functions.
A file that contains a collection of related functions and other definitions.
A statement that reads a module file and creates a module object.
A value created by an import statement that provides access to the values defined in a module.
The syntax for calling a function in another module by specifying the module name followed by a dot (period) and the function name.
The order statements run in.
A graphical representation of a stack of functions, their variables, and the values they refer to.
A box in a stack diagram that represents a function call. It contains the local variables and parameters of the function.
A list of the functions that are executing, printed when an exception occurs.
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.
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.
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:
Here’s an example that uses do_twice
to call a function
named print_spam
twice.
Type this example into a script and test it.
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.
Copy the definition of
print_twice
from earlier in this chapter to your script.
Use the modified version of do_twice
to call
print_twice
twice, passing ’spam’
as an argument.
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.
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:
By default, print advances to the next line, but you can override that behavior and put a space at the end, like this:
The output of these statements is ’+ -’
on the same line.
The output from the next print statement would begin on the next line.
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.