Archive:Think Python/Functions: Difference between revisions

wikademia>Whiteknight
m Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step
 
wikademia>Whiteknight
m Partial (mostly) conversion from HTML to Wikitext
Line 1: Line 1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
{{Think Python/Page}}
            "http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>


<META http-equiv="Content-Type" content="text/html; charset=US-ASCII">
== Chapter&#XA0;3&#XA0;&#XA0;Functions ==
<META name="GENERATOR" content="hevea 1.10">
 
<LINK rel="stylesheet" type="text/css" href="book.css">
 
<TITLE>Functions</TITLE>
 
</HEAD>
=== 3.1&#XA0;&#XA0;Function calls ===
<BODY >
 
<A HREF="book003.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
 
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
 
<A HREF="book005.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
 
<HR>
 
<H1 CLASS="chapter"><A NAME="htoc28"><FONT COLOR=black><FONT SIZE=3>Chapter&#XA0;3</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Functions</FONT></FONT></H1><P><FONT COLOR=black><FONT SIZE=3>
In the context of programming, a '''function''' is a named sequence of
</FONT></FONT><A NAME="funcchap"></A></P><H2 CLASS="section"><A NAME="toc24"></A><A NAME="htoc29"><FONT COLOR=black><FONT SIZE=3>3.1</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Function calls</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</FONT></FONT><A NAME="functionchap"></A><FONT COLOR=black><FONT SIZE=3>
</FONT></FONT><A NAME="@default185"></A></P><P><FONT COLOR=black><FONT SIZE=3>In the context of programming, a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>function</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is a named sequence of
statements that performs a computation. When you define a function,
statements that performs a computation. When you define a function,
you specify the name and the sequence of statements. Later, you can
you specify the name and the sequence of statements. Later, you can
&#X201C;call&#X201D; the function by name.  
&#X201C;call&#X201D; the function by name.  
We have already seen one example of a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>function call</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; type(32)
We have already seen one example of a '''function call''':
<PRE CLASS="verbatim">&gt;&gt;&gt; type(32)
&lt;type 'int'&gt;
&lt;type 'int'&gt;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The name of the function is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>type</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. The expression in parentheses
</PRE>
is called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>argument</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> of the function. The result, for this
The name of the function is <TT>type</TT>. The expression in parentheses
function, is the type of the argument.</FONT></FONT></P><P><A NAME="@default186"></A></P><P><FONT COLOR=black><FONT SIZE=3>It is common to say that a function &#X201C;takes&#X201D; an argument and &#X201C;returns&#X201D;
is called the '''argument''' of the function. The result, for this
a result. The result is called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>return value</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default187"></A><FONT COLOR=black><FONT SIZE=3>
function, is the type of the argument.
</FONT></FONT><A NAME="@default188"></A></P><H2 CLASS="section"><A NAME="toc25"></A><A NAME="htoc30"><FONT COLOR=black><FONT SIZE=3>3.2</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Type conversion functions</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default189"></A><FONT COLOR=black><FONT SIZE=3>
It is common to say that a function &#X201C;takes&#X201D; an argument and &#X201C;returns&#X201D;
</FONT></FONT><A NAME="@default190"></A></P><P><FONT COLOR=black><FONT SIZE=3>Python provides built-in functions that convert values
a result. The result is called the '''return value'''.
from one type to another. The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>int</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> function takes any value and
 
converts it to an integer, if it can, or complains otherwise:</FONT></FONT></P><P><A NAME="@default191"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default192"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; int('32')
 
=== 3.2&#XA0;&#XA0;Type conversion functions ===
 
 
 
 
 
Python provides built-in functions that convert values
from one type to another. The <TT>int</TT> function takes any value and
converts it to an integer, if it can, or complains otherwise:
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; int('32')
32
32
&gt;&gt;&gt; int('Hello')
&gt;&gt;&gt; int('Hello')
ValueError: invalid literal for int(): Hello
ValueError: invalid literal for int(): Hello
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3><TT>int</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> can convert floating-point values to integers, but it
</PRE>
doesn&#X2019;t round off; it chops off the fraction part:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; int(3.99999)
<TT>int</TT> can convert floating-point values to integers, but it
doesn&#X2019;t round off; it chops off the fraction part:
<PRE CLASS="verbatim">&gt;&gt;&gt; int(3.99999)
3
3
&gt;&gt;&gt; int(-2.3)
&gt;&gt;&gt; int(-2.3)
-2
-2
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3><TT>float</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> converts integers and strings to floating-point
</PRE>
numbers:</FONT></FONT></P><P><A NAME="@default193"></A><FONT COLOR=black><FONT SIZE=3>
<TT>float</TT> converts integers and strings to floating-point
</FONT></FONT><A NAME="@default194"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; float(32)
numbers:
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; float(32)
32.0
32.0
&gt;&gt;&gt; float('3.14159')
&gt;&gt;&gt; float('3.14159')
3.14159
3.14159
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Finally, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>str</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> converts its argument to a string:</FONT></FONT></P><P><A NAME="@default195"></A><FONT COLOR=black><FONT SIZE=3>
</PRE>
</FONT></FONT><A NAME="@default196"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; str(32)
Finally, <TT>str</TT> converts its argument to a string:
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; str(32)
'32'
'32'
&gt;&gt;&gt; str(3.14159)
&gt;&gt;&gt; str(3.14159)
'3.14159'
'3.14159'
</FONT></FONT></PRE><H2 CLASS="section"><A NAME="toc26"></A><A NAME="htoc31"><FONT COLOR=black><FONT SIZE=3>3.3</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Math functions</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</PRE>=== 3.3&#XA0;&#XA0;Math functions ===
</FONT></FONT><A NAME="@default197"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default198"></A></P><P><FONT COLOR=black><FONT SIZE=3>Python has a math module that provides most of the familiar
 
mathematical functions. A </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>module</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is a file that contains a
 
collection of related functions.</FONT></FONT></P><P><A NAME="@default199"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default200"></A></P><P><FONT COLOR=black><FONT SIZE=3>Before we can use the module, we have to import it:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; import math
 
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This statement creates a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>module object</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> named math. If
Python has a math module that provides most of the familiar
you print the module object, you get some information about it:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print math
mathematical functions. A '''module''' is a file that contains a
collection of related functions.
 
 
 
 
Before we can use the module, we have to import it:
<PRE CLASS="verbatim">&gt;&gt;&gt; import math
</PRE>
This statement creates a '''module object''' named math. If
you print the module object, you get some information about it:
<PRE CLASS="verbatim">&gt;&gt;&gt; print math
&lt;module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'&gt;
&lt;module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'&gt;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The module object contains the functions and variables defined in the
</PRE>
The module object contains the functions and variables defined in the
module. To access one of the functions, you have to specify the name
module. To access one of the functions, you have to specify the name
of the module and the name of the function, separated by a dot (also
of the module and the name of the function, separated by a dot (also
known as a period). This format is called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>dot notation</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default201"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; ratio = signal_power / noise_power
known as a period). This format is called '''dot notation'''.
 
<PRE CLASS="verbatim">&gt;&gt;&gt; ratio = signal_power / noise_power
&gt;&gt;&gt; decibels = 10 * math.log10(ratio)
&gt;&gt;&gt; decibels = 10 * math.log10(ratio)


&gt;&gt;&gt; radians = 0.7
&gt;&gt;&gt; radians = 0.7
&gt;&gt;&gt; height = math.sin(radians)
&gt;&gt;&gt; height = math.sin(radians)
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The first example computes the logarithm base 10 of the
</PRE>
The first example computes the logarithm base 10 of the
signal-to-noise ratio. The math module also provides a
signal-to-noise ratio. The math module also provides a
function called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>log</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> that computes logarithms base </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>e</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default202"></A><FONT COLOR=black><FONT SIZE=3>
function called <TT>log</TT> that computes logarithms base <TT>e</TT>.
</FONT></FONT><A NAME="@default203"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default204"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default205"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default206"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default207"></A></P><P><FONT COLOR=black><FONT SIZE=3>The second example finds the sine of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>radians</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. The name of the
 
variable is a hint that </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>sin</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> and the other trigonometric
 
functions (</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>cos</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>tan</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, etc.) take arguments in radians. To
 
convert from degrees to radians, divide by 360 and multiply by </FONT></FONT><FONT COLOR=black><FONT SIZE=3>2
 
&#X3C0;</FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; degrees = 45
The second example finds the sine of <TT>radians</TT>. The name of the
variable is a hint that <TT>sin</TT> and the other trigonometric
functions (<TT>cos</TT>, <TT>tan</TT>, etc.) take arguments in radians. To
convert from degrees to radians, divide by 360 and multiply by 2
&#X3C0;:
<PRE CLASS="verbatim">&gt;&gt;&gt; degrees = 45
&gt;&gt;&gt; radians = degrees / 360.0 * 2 * math.pi
&gt;&gt;&gt; radians = degrees / 360.0 * 2 * math.pi
&gt;&gt;&gt; math.sin(radians)
&gt;&gt;&gt; math.sin(radians)
0.707106781187
0.707106781187
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The expression </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>math.pi</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> gets the variable </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>pi</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> from the math
</PRE>
The expression <TT>math.pi</TT> gets the variable <TT>pi</TT> from the math
module. The value of this variable is an approximation
module. The value of this variable is an approximation
of </FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#X3C0;</FONT></FONT><FONT COLOR=black><FONT SIZE=3>, accurate to about 15 digits.</FONT></FONT></P><P><A NAME="@default208"></A></P><P><FONT COLOR=black><FONT SIZE=3>If you know
of &#X3C0;, accurate to about 15 digits.
 
If you know
your trigonometry, you can check the previous result by comparing it to
your trigonometry, you can check the previous result by comparing it to
the square root of two divided by two:</FONT></FONT></P><P><A NAME="@default209"></A><FONT COLOR=black><FONT SIZE=3>
the square root of two divided by two:
</FONT></FONT><A NAME="@default210"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; math.sqrt(2) / 2.0
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; math.sqrt(2) / 2.0
0.707106781187
0.707106781187
</FONT></FONT></PRE><H2 CLASS="section"><A NAME="toc27"></A><A NAME="htoc32"><FONT COLOR=black><FONT SIZE=3>3.4</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Composition</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</PRE>=== 3.4&#XA0;&#XA0;Composition ===
</FONT></FONT><A NAME="@default211"></A></P><P><FONT COLOR=black><FONT SIZE=3>So far, we have looked at the elements of a program&#X2014;variables,
 
 
 
 
So far, we have looked at the elements of a program&#X2014;variables,
expressions, and statements&#X2014;in isolation, without talking about how to
expressions, and statements&#X2014;in isolation, without talking about how to
combine them.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>One of the most useful features of programming languages is their
combine them.
ability to take small building blocks and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>compose</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> them. For
 
One of the most useful features of programming languages is their
ability to take small building blocks and '''compose''' them. For
example, the argument of a function can be any kind of expression,
example, the argument of a function can be any kind of expression,
including arithmetic operators:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>x = math.sin(degrees / 360.0 * 2 * math.pi)
including arithmetic operators:
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>And even function calls:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>x = math.exp(math.log(x+1))
<PRE CLASS="verbatim">x = math.sin(degrees / 360.0 * 2 * math.pi)
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Almost anywhere you can put a value, you can put an arbitrary
</PRE>
And even function calls:
<PRE CLASS="verbatim">x = math.exp(math.log(x+1))
</PRE>
Almost anywhere you can put a value, you can put an arbitrary
expression, with one exception: the left side of an assignment
expression, with one exception: the left side of an assignment
statement has to be a variable name. Any other expression on the left
statement has to be a variable name. Any other expression on the left
side is a syntax error</FONT></FONT><SUP><A NAME="text5" HREF="#note5"><FONT COLOR=black><FONT SIZE=3>1</FONT></FONT></A></SUP><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; minutes = hours * 60                # right
side is a syntax error<SUP>1</SUP>.
<PRE CLASS="verbatim">&gt;&gt;&gt; minutes = hours * 60                # right
&gt;&gt;&gt; hours * 60 = minutes                # wrong!
&gt;&gt;&gt; hours * 60 = minutes                # wrong!
SyntaxError: can't assign to operator
SyntaxError: can't assign to operator
</FONT></FONT></PRE><P><A NAME="@default212"></A><FONT COLOR=black><FONT SIZE=3>
</PRE>
</FONT></FONT><A NAME="@default213"></A></P><H2 CLASS="section"><A NAME="toc28"></A><A NAME="htoc33"><FONT COLOR=black><FONT SIZE=3>3.5</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Adding new functions</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>So far, we have only been using the functions that come with Python,
 
 
=== 3.5&#XA0;&#XA0;Adding new functions ===
 
So far, we have only been using the functions that come with Python,
but it is also possible to add new functions.
but it is also possible to add new functions.
A </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>function definition</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> specifies the name of a new function and
A '''function definition''' specifies the name of a new function and
the sequence of statements that execute when the function is called.</FONT></FONT></P><P><A NAME="@default214"></A><FONT COLOR=black><FONT SIZE=3>
the sequence of statements that execute when the function is called.
</FONT></FONT><A NAME="@default215"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default216"></A></P><P><FONT COLOR=black><FONT SIZE=3>Here is an example:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def print_lyrics():
 
 
 
 
Here is an example:
<PRE CLASS="verbatim">def print_lyrics():
     print "I'm a lumberjack, and I'm okay."
     print "I'm a lumberjack, and I'm okay."
     print "I sleep all night and I work all day."
     print "I sleep all night and I work all day."
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3><TT>def</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is a keyword that indicates that this is a function
</PRE>
definition. The name of the function is </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>. The
<TT>def</TT> is a keyword that indicates that this is a function
definition. The name of the function is <CODE>print_lyrics</CODE>. The
rules for function names are the same as for variable names: letters,
rules for function names are the same as for variable names: letters,
numbers and some punctuation marks are legal, but the first character
numbers and some punctuation marks are legal, but the first character
can&#X2019;t be a number. You can&#X2019;t use a keyword as the name of a function,
can&#X2019;t be a number. You can&#X2019;t use a keyword as the name of a function,
and you should avoid having a variable and a function with the same
and you should avoid having a variable and a function with the same
name.</FONT></FONT></P><P><A NAME="@default217"></A><FONT COLOR=black><FONT SIZE=3>
name.
</FONT></FONT><A NAME="@default218"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default219"></A></P><P><FONT COLOR=black><FONT SIZE=3>The empty parentheses after the name indicate that this function
 
doesn&#X2019;t take any arguments.</FONT></FONT></P><P><A NAME="@default220"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default221"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default222"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default223"></A><FONT COLOR=black><FONT SIZE=3>
The empty parentheses after the name indicate that this function
</FONT></FONT><A NAME="@default224"></A></P><P><FONT COLOR=black><FONT SIZE=3>The first line of the function definition is called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>header</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>;
doesn&#X2019;t take any arguments.
the rest is called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>body</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. The header has to end with a colon
 
 
 
 
 
 
 
The first line of the function definition is called the '''header''';
the rest is called the '''body'''. The header has to end with a colon
and the body has to be indented. By convention, the indentation is
and the body has to be indented. By convention, the indentation is
always four spaces (see Section&#XA0;</FONT></FONT><A HREF="#editor"><FONT COLOR=black><FONT SIZE=3>3.13</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>). The body can contain
always four spaces (see Section&#XA0;3.13). The body can contain
any number of statements.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>The strings in the print statements are enclosed in double
any number of statements.
 
The strings in the print statements are enclosed in double
quotes. Single quotes and double quotes do the same thing;
quotes. Single quotes and double quotes do the same thing;
most people use single quotes except in cases like this where
most people use single quotes except in cases like this where
a single quote (which is also an apostrophe) appears in the string.</FONT></FONT></P><P><A NAME="@default225"></A></P><P><FONT COLOR=black><FONT SIZE=3>If you type a function definition in interactive mode, the interpreter
a single quote (which is also an apostrophe) appears in the string.
prints ellipses (</FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>...</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3>) to let you know that the definition
 
isn&#X2019;t complete:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; def print_lyrics():
If you type a function definition in interactive mode, the interpreter
prints ellipses (''...'') to let you know that the definition
isn&#X2019;t complete:
<PRE CLASS="verbatim">&gt;&gt;&gt; def print_lyrics():
...    print "I'm a lumberjack, and I'm okay."
...    print "I'm a lumberjack, and I'm okay."
...    print "I sleep all night and I work all day."
...    print "I sleep all night and I work all day."
...
...
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>To end the function, you have to enter an empty line (this is
</PRE>
not necessary in a script).</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Defining a function creates a variable with the same name.</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print print_lyrics
To end the function, you have to enter an empty line (this is
not necessary in a script).
 
Defining a function creates a variable with the same name.
<PRE CLASS="verbatim">&gt;&gt;&gt; print print_lyrics
&lt;function print_lyrics at 0xb7e99e9c&gt;
&lt;function print_lyrics at 0xb7e99e9c&gt;
&gt;&gt;&gt; print type(print_lyrics)
&gt;&gt;&gt; print type(print_lyrics)
&lt;type 'function'&gt;
&lt;type 'function'&gt;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The value of </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> is a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>function object</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, which
</PRE>
has type </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>'function'</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default226"></A><FONT COLOR=black><FONT SIZE=3>
The value of <CODE>print_lyrics</CODE> is a '''function object''', which
</FONT></FONT><A NAME="@default227"></A></P><P><FONT COLOR=black><FONT SIZE=3>The syntax for calling the new function is the same as
has type <CODE>'function'</CODE>.
for built-in functions:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print_lyrics()
 
 
 
 
The syntax for calling the new function is the same as
for built-in functions:
<PRE CLASS="verbatim">&gt;&gt;&gt; print_lyrics()
I'm a lumberjack, and I'm okay.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I sleep all night and I work all day.
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Once you have defined a function, you can use it inside another
</PRE>
Once you have defined a function, you can use it inside another
function. For example, to repeat the previous refrain, we could write
function. For example, to repeat the previous refrain, we could write
a function called </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>repeat_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def repeat_lyrics():
a function called <CODE>repeat_lyrics</CODE>:
<PRE CLASS="verbatim">def repeat_lyrics():
     print_lyrics()
     print_lyrics()
     print_lyrics()
     print_lyrics()
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>And then call </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>repeat_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; repeat_lyrics()
</PRE>
And then call <CODE>repeat_lyrics</CODE>:
<PRE CLASS="verbatim">&gt;&gt;&gt; repeat_lyrics()
I'm a lumberjack, and I'm okay.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I sleep all night and I work all day.
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>But that&#X2019;s not really how the song goes.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc29"></A><A NAME="htoc34"><FONT COLOR=black><FONT SIZE=3>3.6</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Definitions and uses</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</PRE>
</FONT></FONT><A NAME="@default228"></A></P><P><FONT COLOR=black><FONT SIZE=3>Pulling together the code fragments from the previous section, the
But that&#X2019;s not really how the song goes.
whole program looks like this:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def print_lyrics():
=== 3.6&#XA0;&#XA0;Definitions and uses ===
 
 
 
 
Pulling together the code fragments from the previous section, the
whole program looks like this:
<PRE CLASS="verbatim">def print_lyrics():
     print "I'm a lumberjack, and I'm okay."
     print "I'm a lumberjack, and I'm okay."
     print "I sleep all night and I work all day."
     print "I sleep all night and I work all day."
Line 172: Line 271:


repeat_lyrics()
repeat_lyrics()
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This program contains two function definitions: </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> and
</PRE>
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>repeat_lyrics</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>. Function definitions get executed just like other
This program contains two function definitions: <CODE>print_lyrics</CODE> and
<CODE>repeat_lyrics</CODE>. Function definitions get executed just like other
statements, but the effect is to create function objects. The statements
statements, but the effect is to create function objects. The statements
inside the function do not get executed until the function is called, and
inside the function do not get executed until the function is called, and
the function definition generates no output.</FONT></FONT></P><P><A NAME="@default229"></A></P><P><FONT COLOR=black><FONT SIZE=3>As you might expect, you have to create a function before you can
the function definition generates no output.
 
As you might expect, you have to create a function before you can
execute it. In other words, the function definition has to be
execute it. In other words, the function definition has to be
executed before the first time it is called.</FONT></FONT></P><DIV CLASS="theorem"><FONT COLOR=black><FONT SIZE=3><B>Exercise&#XA0;1</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;<EM>
executed before the first time it is called.
<DIV CLASS="theorem">'''Exercise&#XA0;1'''&#XA0;&#XA0;''
Move the last line of this program
Move the last line of this program
to the top, so the function call appears before the definitions. Run  
to the top, so the function call appears before the definitions. Run  
the program and see what error
the program and see what error
message you get.
message you get.
</EM></FONT></FONT></DIV><DIV CLASS="theorem"><FONT COLOR=black><FONT SIZE=3><B>Exercise&#XA0;2</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;<EM>
''</DIV><DIV CLASS="theorem">'''Exercise&#XA0;2'''&#XA0;&#XA0;''
Move the function call back to the bottom
Move the function call back to the bottom
and move the definition of </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>print_lyrics</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> after the definition of
and move the definition of ''<CODE>''print_lyrics''</CODE>'' after the definition of
</EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>repeat_lyrics</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM>. What happens when you run this program?
''<CODE>''repeat_lyrics''</CODE>''. What happens when you run this program?
</EM></FONT></FONT></DIV><H2 CLASS="section"><A NAME="toc30"></A><A NAME="htoc35"><FONT COLOR=black><FONT SIZE=3>3.7</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Flow of execution</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
''</DIV>=== 3.7&#XA0;&#XA0;Flow of execution ===
</FONT></FONT><A NAME="@default230"></A></P><P><FONT COLOR=black><FONT SIZE=3>In order to ensure that a function is defined before its first use,
 
 
 
 
In order to ensure that a function is defined before its first use,
you have to know the order in which statements are executed, which is
you have to know the order in which statements are executed, which is
called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>flow of execution</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Execution always begins at the first statement of the program.
called the '''flow of execution'''.
Statements are executed one at a time, in order from top to bottom.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Function definitions do not alter the flow of execution of the
 
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to bottom.
 
Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
program, but remember that statements inside the function are not
executed until the function is called.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>A function call is like a detour in the flow of execution. Instead of
executed until the function is called.
 
A function call is like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the body of
going to the next statement, the flow jumps to the body of
the function, executes all the statements there, and then comes back
the function, executes all the statements there, and then comes back
to pick up where it left off.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>That sounds simple enough, until you remember that one function can
to pick up where it left off.
 
That sounds simple enough, until you remember that one function can
call another. While in the middle of one function, the program might
call another. While in the middle of one function, the program might
have to execute the statements in another function. But while
have to execute the statements in another function. But while
executing that new function, the program might have to execute yet
executing that new function, the program might have to execute yet
another function!</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Fortunately, Python is good at keeping track of where it is, so each
another function!
 
Fortunately, Python is good at keeping track of where it is, so each
time a function completes, the program picks up where it left off in
time a function completes, the program picks up where it left off in
the function that called it. When it gets to the end of the program,
the function that called it. When it gets to the end of the program,
it terminates.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>What&#X2019;s the moral of this sordid tale? When you read a program, you
it terminates.
 
What&#X2019;s the moral of this sordid tale? When you read a program, you
don&#X2019;t always want to read from top to bottom. Sometimes it makes
don&#X2019;t always want to read from top to bottom. Sometimes it makes
more sense if you follow the flow of execution.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc31"></A><A NAME="htoc36"><FONT COLOR=black><FONT SIZE=3>3.8</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Parameters and arguments</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
more sense if you follow the flow of execution.
</FONT></FONT><A NAME="parameters"></A><FONT COLOR=black><FONT SIZE=3>
=== 3.8&#XA0;&#XA0;Parameters and arguments ===
</FONT></FONT><A NAME="@default231"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default232"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default233"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default234"></A></P><P><FONT COLOR=black><FONT SIZE=3>Some of the built-in functions we have seen require arguments. For
 
example, when you call </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>math.sin</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> you pass a number
 
 
 
 
Some of the built-in functions we have seen require arguments. For
example, when you call <TT>math.sin</TT> you pass a number
as an argument. Some functions take more than one argument:
as an argument. Some functions take more than one argument:
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>math.pow</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> takes two, the base and the exponent.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Inside the function, the arguments are assigned to
<TT>math.pow</TT> takes two, the base and the exponent.
variables called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>parameters</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. Here is an example of a
 
user-defined function that takes an argument:</FONT></FONT></P><P><A NAME="@default235"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def print_twice(bruce):
Inside the function, the arguments are assigned to
variables called '''parameters'''. Here is an example of a
user-defined function that takes an argument:
 
<PRE CLASS="verbatim">def print_twice(bruce):
     print bruce
     print bruce
     print bruce
     print bruce
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This function assigns the argument to a parameter
</PRE>
named </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bruce</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. When the function is called, it prints the value of
This function assigns the argument to a parameter
the parameter (whatever it is) twice.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>This function works with any value that can be printed.</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print_twice('Spam')
named <TT>bruce</TT>. When the function is called, it prints the value of
the parameter (whatever it is) twice.
 
This function works with any value that can be printed.
<PRE CLASS="verbatim">&gt;&gt;&gt; print_twice('Spam')
Spam
Spam
Spam
Spam
Line 229: Line 361:
3.14159265359
3.14159265359
3.14159265359
3.14159265359
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The same rules of composition that apply to built-in functions also
</PRE>
The same rules of composition that apply to built-in functions also
apply to user-defined functions, so we can use any kind of expression
apply to user-defined functions, so we can use any kind of expression
as an argument for </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><P><A NAME="@default236"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print_twice('Spam '*4)
as an argument for <CODE>print_twice</CODE>:
 
<PRE CLASS="verbatim">&gt;&gt;&gt; print_twice('Spam '*4)
Spam Spam Spam Spam
Spam Spam Spam Spam
Spam Spam Spam Spam
Spam Spam Spam Spam
Line 237: Line 372:
-1.0
-1.0
-1.0
-1.0
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The argument is evaluated before the function is called, so
</PRE>
in the examples the expressions </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>'Spam '*4</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> and
The argument is evaluated before the function is called, so
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>math.cos(math.pi)</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> are only evaluated once.</FONT></FONT></P><P><A NAME="@default237"></A></P><P><FONT COLOR=black><FONT SIZE=3>You can also use a variable as an argument:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; michael = 'Eric, the half a bee.'
in the examples the expressions <CODE>'Spam '*4</CODE> and
<TT>math.cos(math.pi)</TT> are only evaluated once.
 
You can also use a variable as an argument:
<PRE CLASS="verbatim">&gt;&gt;&gt; michael = 'Eric, the half a bee.'
&gt;&gt;&gt; print_twice(michael)
&gt;&gt;&gt; print_twice(michael)
Eric, the half a bee.
Eric, the half a bee.
Eric, the half a bee.
Eric, the half a bee.
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The name of the variable we pass as an argument (</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>michael</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>) has
</PRE>
nothing to do with the name of the parameter (</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bruce</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>). It
The name of the variable we pass as an argument (<TT>michael</TT>) has
nothing to do with the name of the parameter (<TT>bruce</TT>). It
doesn&#X2019;t matter what the value was called back home (in the caller);
doesn&#X2019;t matter what the value was called back home (in the caller);
here in </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, we call everybody </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bruce</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc32"></A><A NAME="htoc37"><FONT COLOR=black><FONT SIZE=3>3.9</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Variables and parameters are local</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
here in <CODE>print_twice</CODE>, we call everybody <TT>bruce</TT>.
</FONT></FONT><A NAME="@default238"></A><FONT COLOR=black><FONT SIZE=3>
=== 3.9&#XA0;&#XA0;Variables and parameters are local ===
</FONT></FONT><A NAME="@default239"></A></P><P><FONT COLOR=black><FONT SIZE=3>When you create a variable inside a function, it is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>local</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>,
 
 
 
 
 
When you create a variable inside a function, it is '''local''',
which means that it only
which means that it only
exists inside the function. For example:</FONT></FONT></P><P><A NAME="@default240"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def cat_twice(part1, part2):
exists inside the function. For example:
 
<PRE CLASS="verbatim">def cat_twice(part1, part2):
     cat = part1 + part2
     cat = part1 + part2
     print_twice(cat)
     print_twice(cat)
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This function takes two arguments, concatenates them, and prints
</PRE>
the result twice. Here is an example that uses it:</FONT></FONT></P><P><A NAME="@default241"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; line1 = 'Bing tiddle '
This function takes two arguments, concatenates them, and prints
the result twice. Here is an example that uses it:
 
<PRE CLASS="verbatim">&gt;&gt;&gt; line1 = 'Bing tiddle '
&gt;&gt;&gt; line2 = 'tiddle bang.'
&gt;&gt;&gt; line2 = 'tiddle bang.'
&gt;&gt;&gt; cat_twice(line1, line2)
&gt;&gt;&gt; cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>When </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>cat_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> terminates, the variable </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>cat</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>
</PRE>
is destroyed. If we try to print it, we get an exception:</FONT></FONT></P><P><A NAME="@default242"></A><FONT COLOR=black><FONT SIZE=3>
When <CODE>cat_twice</CODE> terminates, the variable <TT>cat</TT>
</FONT></FONT><A NAME="@default243"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print cat
is destroyed. If we try to print it, we get an exception:
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; print cat
NameError: name 'cat' is not defined
NameError: name 'cat' is not defined
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Parameters are also local.
</PRE>
For example, outside </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, there is no
Parameters are also local.
such thing as </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bruce</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default244"></A></P><H2 CLASS="section"><A NAME="toc33"></A><A NAME="htoc38"><FONT COLOR=black><FONT SIZE=3>3.10</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Stack diagrams</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
For example, outside <CODE>print_twice</CODE>, there is no
</FONT></FONT><A NAME="stackdiagram"></A><FONT COLOR=black><FONT SIZE=3>
such thing as <TT>bruce</TT>.
</FONT></FONT><A NAME="@default245"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default246"></A><FONT COLOR=black><FONT SIZE=3>
=== 3.10&#XA0;&#XA0;Stack diagrams ===
</FONT></FONT><A NAME="@default247"></A></P><P><FONT COLOR=black><FONT SIZE=3>To keep track of which variables can be used where, it is sometimes
 
useful to draw a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>stack diagram</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. Like state diagrams, stack
 
 
 
 
 
 
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
diagrams show the value of each variable, but they also show the
function each variable belongs to.</FONT></FONT></P><P><A NAME="@default248"></A><FONT COLOR=black><FONT SIZE=3>
function each variable belongs to.
</FONT></FONT><A NAME="@default249"></A></P><P><FONT COLOR=black><FONT SIZE=3>Each function is represented by a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>frame</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. A frame is a box
 
 
 
 
Each function is represented by a '''frame'''. A frame is a box
with the name of a function
with the name of a function
beside it and the parameters and variables of the function inside it.
beside it and the parameters and variables of the function inside it.
The stack diagram for the
The stack diagram for the
previous example looks like this:</FONT></FONT></P><DIV CLASS="center"><FONT COLOR=black><FONT SIZE=3><IMG SRC="book004.png"></FONT></FONT></DIV><P><FONT COLOR=black><FONT SIZE=3>The frames are arranged in a stack that indicates which function
previous example looks like this:
called which, and so on. In this example, </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>
<DIV CLASS="center"><IMG SRC="book004.png"></DIV>
was called by </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>cat_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, and </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>cat_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> was called by  
The frames are arranged in a stack that indicates which function
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, which is a special name for the topmost frame. When
called which, and so on. In this example, <CODE>print_twice</CODE>
was called by <CODE>cat_twice</CODE>, and <CODE>cat_twice</CODE> was called by  
<CODE>__main__</CODE>, which is a special name for the topmost frame. When
you create a variable outside of any function, it belongs to  
you create a variable outside of any function, it belongs to  
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Each parameter refers to the same value as its corresponding
<CODE>__main__</CODE>.
argument. So, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>part1</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> has the same value as
 
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>line1</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>part2</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> has the same value as </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>line2</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>,
Each parameter refers to the same value as its corresponding
and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bruce</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> has the same value as </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>cat</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>If an error occurs during a function call, Python prints the
argument. So, <TT>part1</TT> has the same value as
<TT>line1</TT>, <TT>part2</TT> has the same value as <TT>line2</TT>,
and <TT>bruce</TT> has the same value as <TT>cat</TT>.
 
If an error occurs during a function call, Python prints the
name of the function, and the name of the function that called
name of the function, and the name of the function that called
it, and the name of the function that called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>that</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, all the
it, and the name of the function that called ''that'', all the
way back to </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>For example, if you try to access </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>cat</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> from within  
way back to <CODE>__main__</CODE>.
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, you get a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>NameError</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>Traceback (innermost last):
 
For example, if you try to access <TT>cat</TT> from within  
<CODE>print_twice</CODE>, you get a <TT>NameError</TT>:
<PRE CLASS="verbatim">Traceback (innermost last):
   File "test.py", line 13, in __main__
   File "test.py", line 13, in __main__
     cat_twice(line1, line2)
     cat_twice(line1, line2)
Line 297: Line 471:
     print cat
     print cat
NameError: name 'cat' is not defined
NameError: name 'cat' is not defined
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This list of functions is called a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>traceback</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. It tells you what
</PRE>
This list of functions is called a '''traceback'''. It tells you what
program file the error occurred in, and what line, and what functions
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
were executing at the time. It also shows the line of code that
caused the error.</FONT></FONT></P><P><A NAME="@default250"></A></P><P><FONT COLOR=black><FONT SIZE=3>The order of the functions in the traceback is the same as the
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
order of the frames in the stack diagram. The function that is
currently running is at the bottom.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc34"></A><A NAME="htoc39"><FONT COLOR=black><FONT SIZE=3>3.11</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Fruitful functions and void functions</FONT></FONT></H2><P><A NAME="@default251"></A><FONT COLOR=black><FONT SIZE=3>
currently running is at the bottom.
</FONT></FONT><A NAME="@default252"></A><FONT COLOR=black><FONT SIZE=3>
=== 3.11&#XA0;&#XA0;Fruitful functions and void functions ===
</FONT></FONT><A NAME="@default253"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default254"></A><FONT COLOR=black><FONT SIZE=3> </FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Some of the functions we are using, such as the math functions, yield
 
results; for lack of a better name, I call them </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>fruitful
 
functions</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. Other functions, like </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, perform an
 
action but don&#X2019;t return a value. They are called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>void
functions</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>When you call a fruitful function, you almost always
 
Some of the functions we are using, such as the math functions, yield
results; for lack of a better name, I call them '''fruitful
functions'''. Other functions, like <CODE>print_twice</CODE>, perform an
action but don&#X2019;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
want to do something with the result; for example, you might
assign it to a variable or use it as part of an expression:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>x = math.cos(radians)
assign it to a variable or use it as part of an expression:
<PRE CLASS="verbatim">x = math.cos(radians)
golden = (math.sqrt(5) + 1) / 2
golden = (math.sqrt(5) + 1) / 2
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>When you call a function in interactive mode, Python displays
</PRE>
the result:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; math.sqrt(5)
When you call a function in interactive mode, Python displays
the result:
<PRE CLASS="verbatim">&gt;&gt;&gt; math.sqrt(5)
2.2360679774997898
2.2360679774997898
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>But in a script, if you call a fruitful function all by itself,
</PRE>
the return value is lost forever!</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>math.sqrt(5)
But in a script, if you call a fruitful function all by itself,
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This script computes the square root of 5, but since it doesn&#X2019;t store
the return value is lost forever!
or display the result, it is not very useful.</FONT></FONT></P><P><A NAME="@default255"></A><FONT COLOR=black><FONT SIZE=3>
<PRE CLASS="verbatim">math.sqrt(5)
</FONT></FONT><A NAME="@default256"></A></P><P><FONT COLOR=black><FONT SIZE=3>Void functions might display something on the screen or have some
</PRE>
This script computes the square root of 5, but since it doesn&#X2019;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&#X2019;t have a return value. If you try to
other effect, but they don&#X2019;t have a return value. If you try to
assign the result to a variable, you get a special value called
assign the result to a variable, you get a special value called
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>None</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default257"></A><FONT COLOR=black><FONT SIZE=3>
<TT>None</TT>.
</FONT></FONT><A NAME="@default258"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; result = print_twice('Bing')
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; result = print_twice('Bing')
Bing
Bing
Bing
Bing
&gt;&gt;&gt; print result
&gt;&gt;&gt; print result
None
None
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The value </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>None</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is not the same as the string </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>'None'</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>.  
</PRE>
It is a special value that has its own type:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; print type(None)
The value <TT>None</TT> is not the same as the string <CODE>'None'</CODE>.  
It is a special value that has its own type:
<PRE CLASS="verbatim">&gt;&gt;&gt; print type(None)
&lt;type 'NoneType'&gt;
&lt;type 'NoneType'&gt;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The functions we have written so far are all void. We will start
</PRE>
writing fruitful functions in a few chapters.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc35"></A><A NAME="htoc40"><FONT COLOR=black><FONT SIZE=3>3.12</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Why functions?</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
The functions we have written so far are all void. We will start
</FONT></FONT><A NAME="@default259"></A></P><P><FONT COLOR=black><FONT SIZE=3>It may not be clear why it is worth the trouble to divide
writing fruitful functions in a few chapters.
a program into functions. There are several reasons:</FONT></FONT></P><UL CLASS="itemize"><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>Creating a new function gives you an opportunity to name a group
=== 3.12&#XA0;&#XA0;Why functions? ===
of statements, which makes your program easier to read and debug.</FONT></FONT></LI><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>Functions can make a program smaller by eliminating repetitive
 
 
 
 
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
code. Later, if you make a change, you only have
to make it in one place.</FONT></FONT></LI><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>Dividing a long program into functions allows you to debug the
to make it in one place.
parts one at a time and then assemble them into a working whole.</FONT></FONT></LI><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>Well-designed functions are often useful for many programs.
 
Once you write and debug one, you can reuse it.</FONT></FONT></LI></UL><H2 CLASS="section"><A NAME="toc36"></A><A NAME="htoc41"><FONT COLOR=black><FONT SIZE=3>3.13</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Debugging</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
*Dividing a long program into functions allows you to debug the
</FONT></FONT><A NAME="editor"></A><FONT COLOR=black><FONT SIZE=3>
parts one at a time and then assemble them into a working whole.
</FONT></FONT><A NAME="@default260"></A></P><P><FONT COLOR=black><FONT SIZE=3>If you are using a text editor to write your scripts, you might
 
*Well-designed functions are often useful for many programs.
Once you write and debug one, you can reuse it.
 
=== 3.13&#XA0;&#XA0;Debugging ===
 
 
 
 
 
If you are using a text editor to write your scripts, you might
run into problems with spaces and tabs. The best way to avoid
run into problems with spaces and tabs. The best way to avoid
these problems is to use spaces exclusively (no tabs). Most text
these problems is to use spaces exclusively (no tabs). Most text
editors that know about Python do this by default, but some
editors that know about Python do this by default, but some
don&#X2019;t.</FONT></FONT></P><P><A NAME="@default261"></A></P><P><FONT COLOR=black><FONT SIZE=3>Tabs and spaces are usually invisible, which makes them
don&#X2019;t.
 
Tabs and spaces are usually invisible, which makes them
hard to debug, so try to find an editor that manages indentation
hard to debug, so try to find an editor that manages indentation
for you.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Also, don&#X2019;t forget to save your program before you run it. Some
for you.
 
Also, don&#X2019;t forget to save your program before you run it. Some
development environments do this automatically, but some don&#X2019;t.
development environments do this automatically, but some don&#X2019;t.
In that case the program you are looking at in the text editor
In that case the program you are looking at in the text editor
is not the same as the program you are running.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Debugging can take a long time if you keep running the same,
is not the same as the program you are running.
incorrect, program over and over!</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Make sure that the code you are looking at is the code you are running.
 
If you&#X2019;re not sure, put something like </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print 'hello'</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> at the
Debugging can take a long time if you keep running the same,
incorrect, program over and over!
 
Make sure that the code you are looking at is the code you are running.
If you&#X2019;re not sure, put something like <CODE>print 'hello'</CODE> at the
beginning of the program and run it again. If you don&#X2019;t see
beginning of the program and run it again. If you don&#X2019;t see
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>hello</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>, you&#X2019;re not running the right program!</FONT></FONT></P><H2 CLASS="section"><A NAME="toc37"></A><A NAME="htoc42"><FONT COLOR=black><FONT SIZE=3>3.14</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Glossary</FONT></FONT></H2><DL CLASS="description"><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>function:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A named sequence of statements that performs some
<CODE>hello</CODE>, you&#X2019;re not running the right program!
=== 3.14&#XA0;&#XA0;Glossary ===
 
<DL CLASS="description"><DT CLASS="dt-description">'''function:'''</DT><DD CLASS="dd-description"> A named sequence of statements that performs some
useful operation. Functions may or may not take arguments and may or
useful operation. Functions may or may not take arguments and may or
may not produce a result.
may not produce a result.
</FONT></FONT><A NAME="@default262"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>function definition:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A statement that creates a new function,
</DD><DT CLASS="dt-description">'''function definition:'''</DT><DD CLASS="dd-description"> A statement that creates a new function,
specifying its name, parameters, and the statements it executes.
specifying its name, parameters, and the statements it executes.
</FONT></FONT><A NAME="@default263"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>function object:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A value created by a function definition.
</DD><DT CLASS="dt-description">'''function object:'''</DT><DD CLASS="dd-description"> A value created by a function definition.
The name of the function is a variable that refers to a function
The name of the function is a variable that refers to a function
object.
object.
</FONT></FONT><A NAME="@default264"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>header:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The first line of a function definition.
</DD><DT CLASS="dt-description">'''header:'''</DT><DD CLASS="dd-description"> The first line of a function definition.
</FONT></FONT><A NAME="@default265"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>body:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The sequence of statements inside a function definition.
</DD><DT CLASS="dt-description">'''body:'''</DT><DD CLASS="dd-description"> The sequence of statements inside a function definition.
</FONT></FONT><A NAME="@default266"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>parameter:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A name used inside a function to refer to the value
</DD><DT CLASS="dt-description">'''parameter:'''</DT><DD CLASS="dd-description"> A name used inside a function to refer to the value
passed as an argument.
passed as an argument.
</FONT></FONT><A NAME="@default267"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>function call:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A statement that executes a function. It
</DD><DT CLASS="dt-description">'''function call:'''</DT><DD CLASS="dd-description"> A statement that executes a function. It
consists of the function name followed by an argument list.
consists of the function name followed by an argument list.
</FONT></FONT><A NAME="@default268"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>argument:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A value provided to a function when the function is called.
</DD><DT CLASS="dt-description">'''argument:'''</DT><DD CLASS="dd-description"> A value provided to a function when the function is called.
This value is assigned to the corresponding parameter in the function.
This value is assigned to the corresponding parameter in the function.
</FONT></FONT><A NAME="@default269"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>local variable:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A variable defined inside a function. A local
</DD><DT CLASS="dt-description">'''local variable:'''</DT><DD CLASS="dd-description"> A variable defined inside a function. A local
variable can only be used inside its function.
variable can only be used inside its function.
</FONT></FONT><A NAME="@default270"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>return value:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The result of a function. If a function call
</DD><DT CLASS="dt-description">'''return value:'''</DT><DD CLASS="dd-description"> The result of a function. If a function call
is used as an expression, the return value is the value of
is used as an expression, the return value is the value of
the expression.
the expression.
</FONT></FONT><A NAME="@default271"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>fruitful function:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A function that returns a value.
</DD><DT CLASS="dt-description">'''fruitful function:'''</DT><DD CLASS="dd-description"> A function that returns a value.
</FONT></FONT><A NAME="@default272"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>void function:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A function that doesn&#X2019;t return a value.
</DD><DT CLASS="dt-description">'''void function:'''</DT><DD CLASS="dd-description"> A function that doesn&#X2019;t return a value.
</FONT></FONT><A NAME="@default273"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>module:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A file that contains a
</DD><DT CLASS="dt-description">'''module:'''</DT><DD CLASS="dd-description"> A file that contains a
collection of related functions and other definitions.
collection of related functions and other definitions.
</FONT></FONT><A NAME="@default274"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>import statement:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A statement that reads a module file and creates
</DD><DT CLASS="dt-description">'''import statement:'''</DT><DD CLASS="dd-description"> A statement that reads a module file and creates
a module object.
a module object.
</FONT></FONT><A NAME="@default275"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default276"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>module object:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A value created by an </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>import</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement
</DD><DT CLASS="dt-description">'''module object:'''</DT><DD CLASS="dd-description"> A value created by an <TT>import</TT> statement
that provides access to the values defined in a module.
that provides access to the values defined in a module.
</FONT></FONT><A NAME="@default277"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>dot notation:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The syntax for calling a function in another
</DD><DT CLASS="dt-description">'''dot notation:'''</DT><DD CLASS="dd-description"> The syntax for calling a function in another
module by specifying the module name followed by a dot (period) and
module by specifying the module name followed by a dot (period) and
the function name.
the function name.
</FONT></FONT><A NAME="@default278"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>composition:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> Using an expression as part of a larger expression,
</DD><DT CLASS="dt-description">'''composition:'''</DT><DD CLASS="dd-description"> Using an expression as part of a larger expression,
or a statement as part of a larger statement.
or a statement as part of a larger statement.
</FONT></FONT><A NAME="@default279"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>flow of execution:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The order in which statements are executed during
</DD><DT CLASS="dt-description">'''flow of execution:'''</DT><DD CLASS="dd-description"> The order in which statements are executed during
a program run.
a program run.
</FONT></FONT><A NAME="@default280"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>stack diagram:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A graphical representation of a stack of functions,
</DD><DT CLASS="dt-description">'''stack diagram:'''</DT><DD CLASS="dd-description"> A graphical representation of a stack of functions,
their variables, and the values they refer to.
their variables, and the values they refer to.
</FONT></FONT><A NAME="@default281"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>frame:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A box in a stack diagram that represents a function call.
</DD><DT CLASS="dt-description">'''frame:'''</DT><DD CLASS="dd-description"> A box in a stack diagram that represents a function call.
It contains the local variables and parameters of the function.
It contains the local variables and parameters of the function.
</FONT></FONT><A NAME="@default282"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default283"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>traceback:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A list of the functions that are executing,
</DD><DT CLASS="dt-description">'''traceback:'''</DT><DD CLASS="dd-description"> A list of the functions that are executing,
printed when an exception occurs.
printed when an exception occurs.
</FONT></FONT><A NAME="@default284"></A></DD></DL><H2 CLASS="section"><A NAME="toc38"></A><A NAME="htoc43"><FONT COLOR=black><FONT SIZE=3>3.15</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Exercises</FONT></FONT></H2><DIV CLASS="theorem"><FONT COLOR=black><FONT SIZE=3><B>Exercise&#XA0;3</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;</FONT></FONT><P><A NAME="@default285"></A><FONT COLOR=black><FONT SIZE=3><EM>
</DD></DL>=== 3.15&#XA0;&#XA0;Exercises ===
</EM></FONT></FONT><A NAME="@default286"></A></P><P><FONT COLOR=black><FONT SIZE=3><EM>Python provides a built-in function called </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>len</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> that
 
returns the length of a string, so the value of </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>len('allen')</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> is 5.</EM></FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3><EM>Write a function named </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>right_justify</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> that takes a string
<DIV CLASS="theorem">'''Exercise&#XA0;3'''&#XA0;&#XA0;
named </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>s</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> as a parameter and prints the string with enough
''
''
 
''Python provides a built-in function called ''''<TT>len</TT>'''' that
returns the length of a string, so the value of ''<CODE>''len('allen')''</CODE>'' is 5.''
 
''Write a function named ''<CODE>''right_justify''</CODE>'' that takes a string
named ''''<TT>s</TT>'''' as a parameter and prints the string with enough
leading spaces so that the last letter of the string is in column 70
leading spaces so that the last letter of the string is in column 70
of the display.</EM></FONT></FONT></P><PRE CLASS="verbatim"><EM><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; right_justify('allen')
of the display.''
<PRE CLASS="verbatim">''&gt;&gt;&gt; right_justify('allen')
                                                                 allen
                                                                 allen
</FONT></FONT></EM></PRE></DIV><DIV CLASS="theorem"><FONT COLOR=black><FONT SIZE=3><B>Exercise&#XA0;4</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;<EM>
''</PRE></DIV><DIV CLASS="theorem">'''Exercise&#XA0;4'''&#XA0;&#XA0;''
</EM></FONT></FONT><A NAME="@default287"></A><FONT COLOR=black><FONT SIZE=3><EM>
''''
</EM></FONT></FONT><A NAME="@default288"></A><P><FONT COLOR=black><FONT SIZE=3><EM>A function object is a value you can assign to a variable
''
or pass as an argument. For example, </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>do_twice</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> is a function
''A function object is a value you can assign to a variable
that takes a function object as an argument and calls it twice:</EM></FONT></FONT></P><PRE CLASS="verbatim"><EM><FONT COLOR=blue><FONT SIZE=4>def do_twice(f):
or pass as an argument. For example, ''<CODE>''do_twice''</CODE>'' is a function
that takes a function object as an argument and calls it twice:''
<PRE CLASS="verbatim">''def do_twice(f):
     f()
     f()
     f()
     f()
</FONT></FONT></EM></PRE><P><EM><FONT COLOR=black><FONT SIZE=3>Here&#X2019;s an example that uses </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>do_twice</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> to call a function
''</PRE>
named </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>print_spam</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> twice.</FONT></FONT></EM></P><PRE CLASS="verbatim"><EM><FONT COLOR=blue><FONT SIZE=4>def print_spam():
''Here&#X2019;s an example that uses ''<CODE>''do_twice''</CODE>'' to call a function
named ''<CODE>''print_spam''</CODE>'' twice.''
<PRE CLASS="verbatim">''def print_spam():
     print 'spam'
     print 'spam'


do_twice(print_spam)
do_twice(print_spam)
</FONT></FONT></EM></PRE><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3>Type this example into a script and test it.</FONT></FONT></EM></LI><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3>Modify </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>do_twice</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> so that it takes two arguments, a
''</PRE>
 
*''Type this example into a script and test it.''
 
*''Modify ''<CODE>''do_twice''</CODE>'' so that it takes two arguments, a
function object and a value, and calls the function twice,
function object and a value, and calls the function twice,
passing the value as an argument.</FONT></FONT></EM></LI><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3>Write a more general version of </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>print_spam</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3>, called
passing the value as an argument.''
</FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3>, that takes a string as a parameter and prints
 
it twice.</FONT></FONT></EM></LI><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3>Use the modified version of </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>do_twice</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> to call
*''Write a more general version of ''<CODE>''print_spam''</CODE>'', called
</FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>print_twice</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> twice, passing </FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>'spam'</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> as an argument.</FONT></FONT></EM></LI><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3>Define a new function called  
''<CODE>''print_twice''</CODE>'', that takes a string as a parameter and prints
</FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3>do_four</FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3> that takes a function object and a value
it twice.''
 
*''Use the modified version of ''<CODE>''do_twice''</CODE>'' to call
''<CODE>''print_twice''</CODE>'' twice, passing ''<CODE>'''spam'''</CODE>'' as an argument.''
 
*''Define a new function called  
''<CODE>''do_four''</CODE>'' that takes a function object and a value
and calls the function four times, passing the value
and calls the function four times, passing the value
as a parameter. There should be only
as a parameter. There should be only
two statements in the body of this function, not four.</FONT></FONT></EM></LI></OL><P><EM><FONT COLOR=black><FONT SIZE=3>You can see my solution at </FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><TT>thinkpython.com/code/do_four.py</TT></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></EM></P></DIV><DIV CLASS="theorem"><FONT COLOR=black><FONT SIZE=3><B>Exercise&#XA0;5</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;<EM>
two statements in the body of this function, not four.''
This exercise</EM></FONT></FONT><SUP><A NAME="text6" HREF="#note6"><FONT COLOR=black><FONT SIZE=3><EM>2</EM></FONT></FONT></A></SUP><FONT COLOR=black><FONT SIZE=3><EM> can be
 
''You can see my solution at ''''<TT>thinkpython.com/code/do_four.py</TT>''''.''
</DIV><DIV CLASS="theorem">'''Exercise&#XA0;5'''&#XA0;&#XA0;''
This exercise''<SUP>''2''</SUP>'' can be
done using only the statements and other features we have learned so
done using only the statements and other features we have learned so
far. </EM></FONT></FONT><P><A NAME="@default289"></A></P><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function that draws a grid like the
far. ''
following:</EM></FONT></FONT><PRE CLASS="verbatim"><EM><FONT COLOR=blue><FONT SIZE=4>+ - - - - + - - - - +
 
*''Write a function that draws a grid like the
following:''<PRE CLASS="verbatim">''+ - - - - + - - - - +
|        |        |
|        |        |
|        |        |
|        |        |
Line 442: Line 699:
|        |        |
|        |        |
+ - - - - + - - - - +
+ - - - - + - - - - +
</FONT></FONT></EM></PRE><P><EM><EM><FONT COLOR=black><FONT SIZE=3>Hint: to print more than one value on a line, you can print
''</PRE>
a comma-separated sequence:</FONT></FONT></EM></EM></P><PRE CLASS="verbatim"><EM><EM><FONT COLOR=blue><FONT SIZE=4>print '+', '-'
''''Hint: to print more than one value on a line, you can print
</FONT></FONT></EM></EM></PRE><P><EM><EM><FONT COLOR=black><FONT SIZE=3>If the sequence ends with a comma, Python leaves the line unfinished,
a comma-separated sequence:''''
so the value printed next appears on the same line.</FONT></FONT></EM></EM></P><PRE CLASS="verbatim"><EM><EM><FONT COLOR=blue><FONT SIZE=4>print '+',  
<PRE CLASS="verbatim">''''print '+', '-'
''''</PRE>
''''If the sequence ends with a comma, Python leaves the line unfinished,
so the value printed next appears on the same line.''''
<PRE CLASS="verbatim">''''print '+',  
print '-'
print '-'
</FONT></FONT></EM></EM></PRE><P><EM><EM><FONT COLOR=black><FONT SIZE=3>The output of these statements is </FONT></FONT></EM></EM><CODE><EM><EM><FONT COLOR=black><FONT SIZE=3>'+ -'</FONT></FONT></EM></EM></CODE><EM><EM><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></EM></EM></P><P><EM><EM><FONT COLOR=black><FONT SIZE=3>A </FONT></FONT></EM></EM><EM><EM><FONT COLOR=black><FONT SIZE=3><TT>print</TT></FONT></FONT></EM></EM><EM><EM><FONT COLOR=black><FONT SIZE=3> statement all by itself ends the current line and
''''</PRE>
goes to the next line.</FONT></FONT></EM></EM></P></LI><LI CLASS="li-enumerate"><EM><EM><FONT COLOR=black><FONT SIZE=3>Use the previous function to draw a similar grid
''''The output of these statements is ''''<CODE>'''''+ -'''''</CODE>''''.''''
with four rows and four columns.</FONT></FONT></EM></EM></LI></OL><P><FONT COLOR=black><FONT SIZE=3><EM>You can see my solution at </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>thinkpython.com/code/grid.py</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></P></DIV><HR CLASS="footnoterule"><DL CLASS="thefootnotes"><DT CLASS="dt-thefootnotes"><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="note5" HREF="#text5"><FONT COLOR=black><FONT SIZE=3>1</FONT></FONT></A></DT><DD CLASS="dd-thefootnotes"><FONT COLOR=black><FONT SIZE=3>We will see exceptions to this rule
''''A ''''''''<TT>print</TT>'''''''' statement all by itself ends the current line and
goes to the next line.''''
 
*''''Use the previous function to draw a similar grid
with four rows and four columns.''''
 
''You can see my solution at ''''<TT>thinkpython.com/code/grid.py</TT>''''.''
</DIV><HR CLASS="footnoterule"><DL CLASS="thefootnotes"><DT CLASS="dt-thefootnotes">
1</DT><DD CLASS="dd-thefootnotes">We will see exceptions to this rule
later.
later.
</FONT></FONT></DD><DT CLASS="dt-thefootnotes"><A NAME="note6" HREF="#text6"><FONT COLOR=black><FONT SIZE=3>2</FONT></FONT></A></DT><DD CLASS="dd-thefootnotes"><FONT COLOR=black><FONT SIZE=3>Based on an exercise in Oualline, <EM>Practical C Programming, Third Edition</EM>, O&#X2019;Reilly (1997)
</DD><DT CLASS="dt-thefootnotes">2</DT><DD CLASS="dd-thefootnotes">Based on an exercise in Oualline, ''Practical C Programming, Third Edition'', O&#X2019;Reilly (1997)
</FONT></FONT></DD></DL>
</DD></DL>
<HR>
<HR>
<A HREF="book003.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
<IMG SRC="previous_motif.gif" ALT="Previous">
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
<IMG SRC="contents_motif.gif" ALT="Up">
<A HREF="book005.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<IMG SRC="next_motif.gif" ALT="Next">
</BODY>
</HTML>