Jump to content

Archive:Think Python/Conditional and recursion: Difference between revisions

From IdeaWazaWiki
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>Wikademia
 
(2 intermediate revisions by 2 users not shown)
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;5&#XA0;&#XA0;Conditionals and recursion ==
<META name="GENERATOR" content="hevea 1.10">
 
<LINK rel="stylesheet" type="text/css" href="book.css">
=== 5.1&#XA0;&#XA0;Modulus operator ===
<TITLE>Conditionals and recursion</TITLE>
 
</HEAD>
 
<BODY >
 
<A HREF="book005.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
 
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
The '''modulus operator''' works on integers and yields the remainder
<A HREF="book007.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<HR>
<H1 CLASS="chapter"><A NAME="htoc57"><FONT COLOR=black><FONT SIZE=3>Chapter&#XA0;5</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Conditionals and recursion</FONT></FONT></H1><H2 CLASS="section"><A NAME="toc51"></A><A NAME="htoc58"><FONT COLOR=black><FONT SIZE=3>5.1</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Modulus operator</FONT></FONT></H2><P><A NAME="@default342"></A><FONT COLOR=black><FONT SIZE=3>
</FONT></FONT><A NAME="@default343"></A></P><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>modulus operator</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> works on integers and yields the remainder
when the first operand is divided by the second. In Python, the
when the first operand is divided by the second. In Python, the
modulus operator is a percent sign (</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>%</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>). The syntax is the same
modulus operator is a percent sign (<CODE>%</CODE>). The syntax is the same
as for other operators:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; quotient = 7 / 3
as for other operators:
<PRE CLASS="verbatim">&gt;&gt;&gt; quotient = 7 / 3
&gt;&gt;&gt; print quotient
&gt;&gt;&gt; print quotient
2
2
Line 24: Line 18:
&gt;&gt;&gt; print remainder
&gt;&gt;&gt; print remainder
1
1
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>So 7 divided by 3 is 2 with 1 left over.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>The modulus operator turns out to be surprisingly useful. For
</PRE>
So 7 divided by 3 is 2 with 1 left over.
 
The modulus operator turns out to be surprisingly useful. For
example, you can check whether one number is divisible by another&#X2014;if
example, you can check whether one number is divisible by another&#X2014;if
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x % y</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is zero, then </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is divisible by </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>y</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default344"></A></P><P><FONT COLOR=black><FONT SIZE=3>Also, you can extract the right-most digit
<TT>x % y</TT> is zero, then <TT>x</TT> is divisible by <TT>y</TT>.
or digits from a number. For example, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x % 10</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> yields the
 
right-most digit of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> (in base 10). Similarly </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x % 100</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>
Also, you can extract the right-most digit
yields the last two digits.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc52"></A><A NAME="htoc59"><FONT COLOR=black><FONT SIZE=3>5.2</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Boolean expressions</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
or digits from a number. For example, <TT>x % 10</TT> yields the
</FONT></FONT><A NAME="@default345"></A><FONT COLOR=black><FONT SIZE=3>
right-most digit of <TT>x</TT> (in base 10). Similarly <TT>x % 100</TT>
</FONT></FONT><A NAME="@default346"></A><FONT COLOR=black><FONT SIZE=3>
yields the last two digits.
</FONT></FONT><A NAME="@default347"></A><FONT COLOR=black><FONT SIZE=3>
=== 5.2&#XA0;&#XA0;Boolean expressions ===
</FONT></FONT><A NAME="@default348"></A></P><P><FONT COLOR=black><FONT SIZE=3>A </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>boolean expression</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is an expression that is either true
 
 
 
 
 
 
 
A '''boolean expression''' is an expression that is either true
or false. The following examples use the  
or false. The following examples use the  
operator </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>==</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, which compares two operands and produces
operator <TT>==</TT>, which compares two operands and produces
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>True</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> if they are equal and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>False</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> otherwise:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; 5 == 5
<TT>True</TT> if they are equal and <TT>False</TT> otherwise:
<PRE CLASS="verbatim">&gt;&gt;&gt; 5 == 5
True
True
&gt;&gt;&gt; 5 == 6
&gt;&gt;&gt; 5 == 6
False
False
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3><TT>True</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>False</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> are special
</PRE>
values that belong to the type </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>bool</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>; they are not strings:</FONT></FONT></P><P><A NAME="@default349"></A><FONT COLOR=black><FONT SIZE=3>
<TT>True</TT> and <TT>False</TT> are special
</FONT></FONT><A NAME="@default350"></A><FONT COLOR=black><FONT SIZE=3>
values that belong to the type <TT>bool</TT>; they are not strings:
</FONT></FONT><A NAME="@default351"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default352"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default353"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default354"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; type(True)
 
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; type(True)
&lt;type 'bool'&gt;
&lt;type 'bool'&gt;
&gt;&gt;&gt; type(False)
&gt;&gt;&gt; type(False)
&lt;type 'bool'&gt;
&lt;type 'bool'&gt;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>==</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> operator is one of the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>comparison operators</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>; the
</PRE>
others are:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>      x != y              # x is not equal to y
The <TT>==</TT> operator is one of the '''comparison operators'''; the
others are:
<PRE CLASS="verbatim">      x != y              # x is not equal to y
       x &gt; y                # x is greater than y
       x &gt; y                # x is greater than y
       x &lt; y                # x is less than y
       x &lt; y                # x is less than y
       x &gt;= y              # x is greater than or equal to y
       x &gt;= y              # x is greater than or equal to y
       x &lt;= y              # x is less than or equal to y
       x &lt;= y              # x is less than or equal to y
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Although these operations are probably familiar to you, the Python
</PRE>
Although these operations are probably familiar to you, the Python
symbols are different from the mathematical symbols. A common error
symbols are different from the mathematical symbols. A common error
is to use a single equal sign (</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>=</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>) instead of a double equal sign
is to use a single equal sign (<TT>=</TT>) instead of a double equal sign
(</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>==</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>). Remember that </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>=</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is an assignment operator and
(<TT>==</TT>). Remember that <TT>=</TT> is an assignment operator and
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>==</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is a comparison operator. There is no such thing as
<TT>==</TT> is a comparison operator. There is no such thing as
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>=&lt;</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> or </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>=&gt;</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default355"></A><FONT COLOR=black><FONT SIZE=3>
<TT>=&lt;</TT> or <TT>=&gt;</TT>.
</FONT></FONT><A NAME="@default356"></A></P><H2 CLASS="section"><A NAME="toc53"></A><A NAME="htoc60"><FONT COLOR=black><FONT SIZE=3>5.3</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Logical operators</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default357"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default358"></A></P><P><FONT COLOR=black><FONT SIZE=3>There are three </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>logical operators</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>: </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>and</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>or</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>not</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. The semantics (meaning) of these operators is
 
=== 5.3&#XA0;&#XA0;Logical operators ===
 
 
 
 
 
There are three '''logical operators''': <TT>and</TT>, <TT>or</TT>, and <TT>not</TT>. The semantics (meaning) of these operators is
similar to their meaning in English. For example,
similar to their meaning in English. For example,
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x &gt; 0 and x &lt; 10</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is true only if </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is greater than 0
<TT>x &gt; 0 and x &lt; 10</TT> is true only if <TT>x</TT> is greater than 0
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>and</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3> less than 10.</FONT></FONT></P><P><A NAME="@default359"></A><FONT COLOR=black><FONT SIZE=3>
''and'' less than 10.
</FONT></FONT><A NAME="@default360"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default361"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default362"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default363"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default364"></A></P><P><FONT COLOR=black><FONT SIZE=3><TT>n%2 == 0 or n%3 == 0</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is true if </FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>either</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3> of the conditions
 
is true, that is, if the number is divisible by 2 </FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>or</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3> 3.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Finally, the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>not</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> operator negates a boolean
 
expression, so </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>not (x &gt; y)</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is true if </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x &gt; y</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is false,
 
that is, if </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is less than or equal to </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>y</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Strictly speaking, the operands of the logical operators should be
 
<TT>n%2 == 0 or n%3 == 0</TT> is true if ''either'' of the conditions
is true, that is, if the number is divisible by 2 ''or'' 3.
 
Finally, the <TT>not</TT> operator negates a boolean
expression, so <TT>not (x &gt; y)</TT> is true if <TT>x &gt; y</TT> is false,
that is, if <TT>x</TT> is less than or equal to <TT>y</TT>.
 
Strictly speaking, the operands of the logical operators should be
boolean expressions, but Python is not very strict.
boolean expressions, but Python is not very strict.
Any nonzero number is interpreted as &#X201C;true.&#X201D;</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; 17 and True
Any nonzero number is interpreted as &#X201C;true.&#X201D;
<PRE CLASS="verbatim">&gt;&gt;&gt; 17 and True
True
True
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This flexibility can be useful, but there are some subtleties to
</PRE>
This flexibility can be useful, but there are some subtleties to
it that might be confusing. You might want to avoid it (unless
it that might be confusing. You might want to avoid it (unless
you know what you are doing).</FONT></FONT></P><H2 CLASS="section"><A NAME="toc54"></A><A NAME="htoc61"><FONT COLOR=black><FONT SIZE=3>5.4</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Conditional execution</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
you know what you are doing).
</FONT></FONT><A NAME="conditional execution"></A></P><P><A NAME="@default365"></A><FONT COLOR=black><FONT SIZE=3>
=== 5.4&#XA0;&#XA0;Conditional execution ===
</FONT></FONT><A NAME="@default366"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default367"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default368"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default369"></A></P><P><FONT COLOR=black><FONT SIZE=3>In order to write useful programs, we almost always need the ability
 
 
 
 
 
 
 
In order to write useful programs, we almost always need the ability
to check conditions and change the behavior of the program
to check conditions and change the behavior of the program
accordingly. </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>Conditional statements</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> give us this ability. The
accordingly. '''Conditional statements''' give us this ability. The
simplest form is the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>if</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if x &gt; 0:
simplest form is the <TT>if</TT> statement:
<PRE CLASS="verbatim">if x &gt; 0:
     print 'x is positive'
     print 'x is positive'
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The boolean expression after the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>if</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement is
</PRE>
called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>condition</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. If it is true, then the indented
The boolean expression after the <TT>if</TT> statement is
statement gets executed. If not, nothing happens.</FONT></FONT></P><P><A NAME="@default370"></A><FONT COLOR=black><FONT SIZE=3>
called the '''condition'''. If it is true, then the indented
</FONT></FONT><A NAME="@default371"></A><FONT COLOR=black><FONT SIZE=3>
statement gets executed. If not, nothing happens.
</FONT></FONT><A NAME="@default372"></A></P><P><FONT COLOR=black><FONT SIZE=3><TT>if</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statements have the same structure as function definitions:
 
 
 
 
 
<TT>if</TT> statements have the same structure as function definitions:
a header followed by an indented block. Statements like this are
a header followed by an indented block. Statements like this are
called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>compound statements</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>There is no limit on the number of statements that can appear in
called '''compound statements'''.
 
There is no limit on the number of statements that can appear in
the body, but there has to be at least one.
the body, but there has to be at least one.
Occasionally, it is useful to have a body with no statements (usually
Occasionally, it is useful to have a body with no statements (usually
as a place keeper for code you haven&#X2019;t written yet). In that
as a place keeper for code you haven&#X2019;t written yet). In that
case, you can use the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>pass</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement, which does nothing.</FONT></FONT></P><P><A NAME="@default373"></A><FONT COLOR=black><FONT SIZE=3>
case, you can use the <TT>pass</TT> statement, which does nothing.
</FONT></FONT><A NAME="@default374"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if x &lt; 0:
 
 
 
<PRE CLASS="verbatim">if x &lt; 0:
     pass          # need to handle negative values!
     pass          # need to handle negative values!
</FONT></FONT></PRE><H2 CLASS="section"><A NAME="toc55"></A><A NAME="htoc62"><FONT COLOR=black><FONT SIZE=3>5.5</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Alternative execution</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</PRE>=== 5.5&#XA0;&#XA0;Alternative execution ===
</FONT></FONT><A NAME="alternative execution"></A></P><P><A NAME="@default375"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default376"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default377"></A></P><P><FONT COLOR=black><FONT SIZE=3>A second form of the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>if</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>alternative execution</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>,
 
 
 
 
 
 
A second form of the <TT>if</TT> statement is '''alternative execution''',
in which there are two possibilities and the condition determines
in which there are two possibilities and the condition determines
which one gets executed. The syntax looks like this:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if x%2 == 0:
which one gets executed. The syntax looks like this:
<PRE CLASS="verbatim">if x%2 == 0:
     print 'x is even'
     print 'x is even'
else:
else:
     print 'x is odd'
     print 'x is odd'
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>If the remainder when </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is divided by 2 is 0, then we
</PRE>
know that </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>x</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is even, and the program displays a message to that
If the remainder when <TT>x</TT> is divided by 2 is 0, then we
know that <TT>x</TT> is even, and the program displays a message to that
effect. If the condition is false, the second set of statements is
effect. If the condition is false, the second set of statements is
executed. Since the condition must be true or false, exactly one of
executed. Since the condition must be true or false, exactly one of
the alternatives will be executed. The alternatives are called
the alternatives will be executed. The alternatives are called
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>branches</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, because they are branches in the flow of execution.</FONT></FONT></P><P><A NAME="@default378"></A></P><H2 CLASS="section"><A NAME="toc56"></A><A NAME="htoc63"><FONT COLOR=black><FONT SIZE=3>5.6</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Chained conditionals</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
'''branches''', because they are branches in the flow of execution.
</FONT></FONT><A NAME="@default379"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default380"></A></P><P><FONT COLOR=black><FONT SIZE=3>Sometimes there are more than two possibilities and we need more than
=== 5.6&#XA0;&#XA0;Chained conditionals ===
two branches. One way to express a computation like that is a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>chained conditional</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if x &lt; y:
 
 
 
 
 
Sometimes there are more than two possibilities and we need more than
two branches. One way to express a computation like that is a '''chained conditional''':
<PRE CLASS="verbatim">if x &lt; y:
     print 'x is less than y'
     print 'x is less than y'
elif x &gt; y:
elif x &gt; y:
Line 127: Line 189:
else:
else:
     print 'x and y are equal'
     print 'x and y are equal'
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3><TT>elif</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is an abbreviation of &#X201C;else if.&#X201D; Again, exactly one
</PRE>
branch will be executed. There is no limit on the number of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>elif</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statements. If there is an </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>else</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> clause, it has to be
<TT>elif</TT> is an abbreviation of &#X201C;else if.&#X201D; Again, exactly one
at the end, but there doesn&#X2019;t have to be one.</FONT></FONT></P><P><A NAME="@default381"></A><FONT COLOR=black><FONT SIZE=3>
branch will be executed. There is no limit on the number of <TT>elif</TT> statements. If there is an <TT>else</TT> clause, it has to be
</FONT></FONT><A NAME="@default382"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if choice == 'a':
at the end, but there doesn&#X2019;t have to be one.
 
 
 
<PRE CLASS="verbatim">if choice == 'a':
     draw_a()
     draw_a()
elif choice == 'b':
elif choice == 'b':
Line 136: Line 202:
elif choice == 'c':
elif choice == 'c':
     draw_c()
     draw_c()
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Each condition is checked in order. If the first is false,
</PRE>
Each condition is checked in order. If the first is false,
the next is checked, and so on. If one of them is
the next is checked, and so on. If one of them is
true, the corresponding branch executes, and the statement
true, the corresponding branch executes, and the statement
ends. Even if more than one condition is true, only the
ends. Even if more than one condition is true, only the
first true branch executes. </FONT></FONT></P><H2 CLASS="section"><A NAME="toc57"></A><A NAME="htoc64"><FONT COLOR=black><FONT SIZE=3>5.7</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Nested conditionals</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
first true branch executes.  
</FONT></FONT><A NAME="@default383"></A><FONT COLOR=black><FONT SIZE=3>
=== 5.7&#XA0;&#XA0;Nested conditionals ===
</FONT></FONT><A NAME="@default384"></A></P><P><FONT COLOR=black><FONT SIZE=3>One conditional can also be nested within another. We could have
 
written the trichotomy example like this:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if x == y:
 
 
 
 
One conditional can also be nested within another. We could have
written the trichotomy example like this:
<PRE CLASS="verbatim">if x == y:
     print 'x and y are equal'
     print 'x and y are equal'
else:
else:
Line 150: Line 223:
     else:
     else:
         print 'x is greater than y'
         print 'x is greater than y'
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The outer conditional contains two branches. The
</PRE>
The outer conditional contains two branches. The
first branch contains a simple statement. The second branch
first branch contains a simple statement. The second branch
contains another </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>if</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement, which has two branches of its
contains another <TT>if</TT> statement, which has two branches of its
own. Those two branches are both simple statements,
own. Those two branches are both simple statements,
although they could have been conditional statements as well.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Although the indentation of the statements makes the structure
although they could have been conditional statements as well.
apparent, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>nested conditionals</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3> become difficult to read very
 
quickly. In general, it is a good idea to avoid them when you can.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Logical operators often provide a way to simplify nested conditional
Although the indentation of the statements makes the structure
apparent, '''nested conditionals''' become difficult to read very
quickly. In general, it is a good idea to avoid them when you can.
 
Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the following code using a
statements. For example, we can rewrite the following code using a
single conditional:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if 0 &lt; x:
single conditional:
<PRE CLASS="verbatim">if 0 &lt; x:
     if x &lt; 10:
     if x &lt; 10:
         print 'x is a positive single-digit number.'
         print 'x is a positive single-digit number.'
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>print</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement is executed only if we make it past both
</PRE>
conditionals, so we can get the same effect with the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>and</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> operator:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>if 0 &lt; x and x &lt; 10:
The <TT>print</TT> statement is executed only if we make it past both
conditionals, so we can get the same effect with the <TT>and</TT> operator:
<PRE CLASS="verbatim">if 0 &lt; x and x &lt; 10:
     print 'x is a positive single-digit number.'
     print 'x is a positive single-digit number.'
</FONT></FONT></PRE><H2 CLASS="section"><A NAME="toc58"></A><A NAME="htoc65"><FONT COLOR=black><FONT SIZE=3>5.8</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Recursion</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
</PRE>=== 5.8&#XA0;&#XA0;Recursion ===
</FONT></FONT><A NAME="recursion"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default385"></A></P><P><FONT COLOR=black><FONT SIZE=3>It is legal for one function to call another;
 
 
 
 
It is legal for one function to call another;
it is also legal for a function to call itself. It may not be obvious
it is also legal for a function to call itself. It may not be obvious
why that is a good thing, but it turns out to be one of the most
why that is a good thing, but it turns out to be one of the most
magical things a program can do.
magical things a program can do.
For example, look at the following function:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def countdown(n):
For example, look at the following function:
<PRE CLASS="verbatim">def countdown(n):
     if n &lt;= 0:
     if n &lt;= 0:
         print 'Blastoff!'
         print 'Blastoff!'
Line 176: Line 262:
         print n
         print n
         countdown(n-1)
         countdown(n-1)
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>If </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is 0 or negative, it outputs the word, &#X201C;Blastoff!&#X201D;
</PRE>
Otherwise, it outputs </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> and then calls a function named </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#X2014;itself&#X2014;passing </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n-1</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> as an argument.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>What happens if we call this function like this?</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; countdown(3)
If <TT>n</TT> is 0 or negative, it outputs the word, &#X201C;Blastoff!&#X201D;
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The execution of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> begins with </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=3</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and since
Otherwise, it outputs <TT>n</TT> and then calls a function named <TT>countdown</TT>&#X2014;itself&#X2014;passing <TT>n-1</TT> as an argument.
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is greater than 0, it outputs the value 3, and then calls itself...</FONT></FONT></P><BLOCKQUOTE CLASS="quote"><FONT COLOR=black><FONT SIZE=3>
 
The execution of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> begins with </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=2</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and since
What happens if we call this function like this?
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is greater than 0, it outputs the value 2, and then calls itself...</FONT></FONT><BLOCKQUOTE CLASS="quote"><FONT COLOR=black><FONT SIZE=3>
<PRE CLASS="verbatim">&gt;&gt;&gt; countdown(3)
The execution of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> begins with </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=1</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and since
</PRE>
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is greater than 0, it outputs the value 1, and then calls itself...</FONT></FONT><BLOCKQUOTE CLASS="quote"><FONT COLOR=black><FONT SIZE=3>
The execution of <TT>countdown</TT> begins with <TT>n=3</TT>, and since
The execution of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> begins with </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=0</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and since </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is not greater than 0, it outputs the word, &#X201C;Blastoff!&#X201D; and then
<TT>n</TT> is greater than 0, it outputs the value 3, and then calls itself...
<BLOCKQUOTE CLASS="quote">
The execution of <TT>countdown</TT> begins with <TT>n=2</TT>, and since
<TT>n</TT> is greater than 0, it outputs the value 2, and then calls itself...<BLOCKQUOTE CLASS="quote">
The execution of <TT>countdown</TT> begins with <TT>n=1</TT>, and since
<TT>n</TT> is greater than 0, it outputs the value 1, and then calls itself...<BLOCKQUOTE CLASS="quote">
The execution of <TT>countdown</TT> begins with <TT>n=0</TT>, and since <TT>n</TT> is not greater than 0, it outputs the word, &#X201C;Blastoff!&#X201D; and then
returns.
returns.
</FONT></FONT></BLOCKQUOTE><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> that got </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=1</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> returns.
</BLOCKQUOTE>
</FONT></FONT></P></BLOCKQUOTE><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> that got </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=2</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> returns.
The <TT>countdown</TT> that got <TT>n=1</TT> returns.
</FONT></FONT></P></BLOCKQUOTE><P><FONT COLOR=black><FONT SIZE=3>The </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> that got </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=3</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> returns.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>And then you&#X2019;re back in </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>. So, the
 
total output looks like this:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>3
</BLOCKQUOTE>
The <TT>countdown</TT> that got <TT>n=2</TT> returns.
 
</BLOCKQUOTE>
The <TT>countdown</TT> that got <TT>n=3</TT> returns.
 
And then you&#X2019;re back in <CODE>__main__</CODE>. So, the
total output looks like this:
<PRE CLASS="verbatim">3
2
2
1
1
Blastoff!
Blastoff!
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>A function that calls itself is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>recursive</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>; the process is
</PRE>
called </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>recursion</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><A NAME="@default386"></A><FONT COLOR=black><FONT SIZE=3>
A function that calls itself is '''recursive'''; the process is
</FONT></FONT><A NAME="@default387"></A></P><P><FONT COLOR=black><FONT SIZE=3>As another example, we can write a function that prints a
called '''recursion'''.
string </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> times.</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def print_n(s, n):
 
 
 
 
As another example, we can write a function that prints a
string <TT>n</TT> times.
<PRE CLASS="verbatim">def print_n(s, n):
     if n &lt;= 0:
     if n &lt;= 0:
         return
         return
     print s
     print s
     print_n(s, n-1)
     print_n(s, n-1)
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>If </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n &lt;= 0</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>return</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> statement exits the function. The
</PRE>
If <TT>n &lt;= 0</TT> the <TT>return</TT> statement exits the function. The
flow of execution immediately returns to the caller, and the remaining
flow of execution immediately returns to the caller, and the remaining
lines of the function are not executed.</FONT></FONT></P><P><A NAME="@default388"></A><FONT COLOR=black><FONT SIZE=3>
lines of the function are not executed.
</FONT></FONT><A NAME="@default389"></A></P><P><FONT COLOR=black><FONT SIZE=3>The rest of the function is similar to </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>: if </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> is
 
greater than 0, it displays </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>s</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> and then calls itself to display
 
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>s</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> </FONT></FONT><FONT COLOR=black><FONT SIZE=3><I>n</I>&#X2212;1</FONT></FONT><FONT COLOR=black><FONT SIZE=3> additional times. So the number of lines of output
 
is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>1 + (n - 1)</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, which adds up to
 
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>For simple examples like this, it is probably easier to use a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>for</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> loop. But we will see examples later that are hard to write
The rest of the function is similar to <TT>countdown</TT>: if <TT>n</TT> is
with a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>for</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> loop and easy to write with recursion, so it is
greater than 0, it displays <TT>s</TT> and then calls itself to display
good to start early.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc59"></A><A NAME="htoc66"><FONT COLOR=black><FONT SIZE=3>5.9</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Stack diagrams for recursive functions</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
<TT>s</TT> <I>n</I>&#X2212;1 additional times. So the number of lines of output
</FONT></FONT><A NAME="@default390"></A><FONT COLOR=black><FONT SIZE=3>
is <TT>1 + (n - 1)</TT>, which adds up to
</FONT></FONT><A NAME="@default391"></A><FONT COLOR=black><FONT SIZE=3>
<TT>n</TT>.
</FONT></FONT><A NAME="@default392"></A></P><P><FONT COLOR=black><FONT SIZE=3>In Section&#XA0;</FONT></FONT><A HREF="book004.html#stackdiagram"><FONT COLOR=black><FONT SIZE=3>3.10</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>, we used a stack diagram to represent
 
For simple examples like this, it is probably easier to use a <TT>for</TT> loop. But we will see examples later that are hard to write
with a <TT>for</TT> loop and easy to write with recursion, so it is
good to start early.
=== 5.9&#XA0;&#XA0;Stack diagrams for recursive functions ===
 
 
 
 
 
 
In Section&#XA0;3.10, we used a stack diagram to represent
the state of a program during a function call. The same kind of
the state of a program during a function call. The same kind of
diagram can help interpret a recursive function.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Every time a function gets called, Python creates a new function
diagram can help interpret a recursive function.
 
Every time a function gets called, Python creates a new function
frame, which contains the function&#X2019;s local variables and parameters.
frame, which contains the function&#X2019;s local variables and parameters.
For a recursive function, there might be more than one frame on the
For a recursive function, there might be more than one frame on the
stack at the same time.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>This figure shows a stack diagram for </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> called with
stack at the same time.
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n = 3</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><DIV CLASS="center"><FONT COLOR=black><FONT SIZE=3><IMG SRC="book007.png"></FONT></FONT></DIV><P><FONT COLOR=black><FONT SIZE=3>As usual, the top of the stack is the frame for </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>.
 
This figure shows a stack diagram for <TT>countdown</TT> called with
<TT>n = 3</TT>:
<DIV CLASS="center"><IMG SRC="book007.png"></DIV>
As usual, the top of the stack is the frame for <CODE>__main__</CODE>.
It is empty because we did not create any variables in  
It is empty because we did not create any variables in  
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>__main__</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> or pass any arguments to it.</FONT></FONT></P><P><A NAME="@default393"></A><FONT COLOR=black><FONT SIZE=3>
<CODE>__main__</CODE> or pass any arguments to it.
</FONT></FONT><A NAME="@default394"></A></P><P><FONT COLOR=black><FONT SIZE=3>The four </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>countdown</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> frames have different values for the
 
parameter </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. The bottom of the stack, where </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=0</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, is
 
called the </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>base case</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>. It does not make a recursive call, so
 
there are no more frames.</FONT></FONT></P><BLOCKQUOTE CLASS="quote"><FONT COLOR=black><FONT SIZE=3>
 
Draw a stack diagram for </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>print_n</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> called with
The four <TT>countdown</TT> frames have different values for the
</FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>s = 'Hello'</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n=2</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.
parameter <TT>n</TT>. The bottom of the stack, where <TT>n=0</TT>, is
</FONT></FONT></BLOCKQUOTE><BLOCKQUOTE CLASS="quote"><FONT COLOR=black><FONT SIZE=3>
called the '''base case'''. It does not make a recursive call, so
Write a function called </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>do_n</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> that takes a function
there are no more frames.
object and a number, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> as arguments, and that calls
<BLOCKQUOTE CLASS="quote">
the given function </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>n</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> times.
Draw a stack diagram for <CODE>print_n</CODE> called with
</FONT></FONT></BLOCKQUOTE><H2 CLASS="section"><A NAME="toc60"></A><A NAME="htoc67"><FONT COLOR=black><FONT SIZE=3>5.10</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Infinite recursion</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
<CODE>s = 'Hello'</CODE> and <TT>n=2</TT>.
</FONT></FONT><A NAME="@default395"></A><FONT COLOR=black><FONT SIZE=3>
</BLOCKQUOTE><BLOCKQUOTE CLASS="quote">
</FONT></FONT><A NAME="@default396"></A><FONT COLOR=black><FONT SIZE=3>
Write a function called <CODE>do_n</CODE> that takes a function
</FONT></FONT><A NAME="@default397"></A><FONT COLOR=black><FONT SIZE=3>
object and a number, <TT>n</TT> as arguments, and that calls
</FONT></FONT><A NAME="@default398"></A><FONT COLOR=black><FONT SIZE=3>
the given function <TT>n</TT> times.
</FONT></FONT><A NAME="@default399"></A></P><P><FONT COLOR=black><FONT SIZE=3>If a recursion never reaches a base case, it goes on making
</BLOCKQUOTE>=== 5.10&#XA0;&#XA0;Infinite recursion ===
 
 
 
 
 
 
 
 
If a recursion never reaches a base case, it goes on making
recursive calls forever, and the program never terminates. This is
recursive calls forever, and the program never terminates. This is
known as </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>infinite recursion</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and it is generally not
known as '''infinite recursion''', and it is generally not
a good idea. Here is a minimal program with an infinite recursion:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>def recurse():
a good idea. Here is a minimal program with an infinite recursion:
<PRE CLASS="verbatim">def recurse():
     recurse()
     recurse()
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>In most programming environments, a program with infinite recursion
</PRE>
In most programming environments, a program with infinite recursion
does not really run forever. Python reports an error
does not really run forever. Python reports an error
message when the maximum recursion depth is reached:</FONT></FONT></P><P><A NAME="@default400"></A><FONT COLOR=black><FONT SIZE=3>
message when the maximum recursion depth is reached:
</FONT></FONT><A NAME="@default401"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>  File "&lt;stdin&gt;", line 2, in recurse
 
 
 
<PRE CLASS="verbatim">  File "&lt;stdin&gt;", line 2, in recurse
   File "&lt;stdin&gt;", line 2, in recurse
   File "&lt;stdin&gt;", line 2, in recurse
   File "&lt;stdin&gt;", line 2, in recurse
   File "&lt;stdin&gt;", line 2, in recurse
Line 253: Line 391:
   File "&lt;stdin&gt;", line 2, in recurse
   File "&lt;stdin&gt;", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded
RuntimeError: Maximum recursion depth exceeded
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>This traceback is a little bigger than the one we saw in the
</PRE>
This traceback is a little bigger than the one we saw in the
previous chapter. When the error occurs, there are 1000
previous chapter. When the error occurs, there are 1000
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>recurse</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> frames on the stack!</FONT></FONT></P><H2 CLASS="section"><A NAME="toc61"></A><A NAME="htoc68"><FONT COLOR=black><FONT SIZE=3>5.11</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Keyboard input</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
<TT>recurse</TT> frames on the stack!
</FONT></FONT><A NAME="@default402"></A></P><P><FONT COLOR=black><FONT SIZE=3>The programs we have written so far are a bit rude in the sense that
=== 5.11&#XA0;&#XA0;Keyboard input ===
 
 
 
 
The programs we have written so far are a bit rude in the sense that
they accept no input from the user. They just do the same thing every
they accept no input from the user. They just do the same thing every
time.</FONT></FONT></P><P><FONT COLOR=black><FONT SIZE=3>Python provides a built-in function called </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>raw_input</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> that gets
time.
input from the keyboard</FONT></FONT><SUP><A NAME="text7" HREF="#note7"><FONT COLOR=black><FONT SIZE=3>1</FONT></FONT></A></SUP><FONT COLOR=black><FONT SIZE=3>. When this function is called, the program stops and
 
waits for the user to type something. When the user presses </FONT></FONT><FONT SIZE=3><FONT COLOR=purple>Return</FONT></FONT><FONT COLOR=black><FONT SIZE=3> or </FONT></FONT><FONT SIZE=3><FONT COLOR=purple>Enter</FONT></FONT><FONT COLOR=black><FONT SIZE=3>, the program resumes and </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>raw_input</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3>
Python provides a built-in function called <CODE>raw_input</CODE> that gets
returns what the user typed as a string.</FONT></FONT></P><P><A NAME="@default403"></A><FONT COLOR=black><FONT SIZE=3>
input from the keyboard<SUP>1</SUP>. When this function is called, the program stops and
</FONT></FONT><A NAME="@default404"></A><FONT COLOR=black><FONT SIZE=3>
waits for the user to type something. When the user presses Return or Enter, the program resumes and <CODE>raw_input</CODE>
</FONT></FONT><A NAME="@default405"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; input = raw_input()
returns what the user typed as a string.
 
 
 
 
<PRE CLASS="verbatim">&gt;&gt;&gt; input = raw_input()
What are you waiting for?
What are you waiting for?
&gt;&gt;&gt; print input
&gt;&gt;&gt; print input
What are you waiting for?
What are you waiting for?
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>Before getting input from the user, it is a good idea to print a
</PRE>
prompt telling the user what to input. </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>raw_input</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> can take a
Before getting input from the user, it is a good idea to print a
prompt as an argument:</FONT></FONT></P><P><A NAME="@default406"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; name = raw_input('What...is your name?\n')
prompt telling the user what to input. <CODE>raw_input</CODE> can take a
prompt as an argument:
 
<PRE CLASS="verbatim">&gt;&gt;&gt; name = raw_input('What...is your name?\n')
What...is your name?
What...is your name?
Arthur, King of the Britons!
Arthur, King of the Britons!
&gt;&gt;&gt; print name
&gt;&gt;&gt; print name
Arthur, King of the Britons!
Arthur, King of the Britons!
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The sequence </FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3>\n</FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3> at the end of the prompt represents a </FONT></FONT><FONT COLOR=black><FONT SIZE=3><B>newline</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>,
</PRE>
The sequence <CODE>\n</CODE> at the end of the prompt represents a '''newline''',
which is a special character that causes a line break.
which is a special character that causes a line break.
That&#X2019;s why the user&#X2019;s input appears below the prompt.</FONT></FONT></P><P><A NAME="@default407"></A></P><P><FONT COLOR=black><FONT SIZE=3>If you expect the user to type an integer, you can try to convert
That&#X2019;s why the user&#X2019;s input appears below the prompt.
the return value to </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>int</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
 
If you expect the user to type an integer, you can try to convert
the return value to <TT>int</TT>:
<PRE CLASS="verbatim">&gt;&gt;&gt; prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
&gt;&gt;&gt; speed = raw_input(prompt)
&gt;&gt;&gt; speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What...is the airspeed velocity of an unladen swallow?
Line 283: Line 439:
&gt;&gt;&gt; int(speed)
&gt;&gt;&gt; int(speed)
17
17
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>But if the user types something other than a string of digits,
</PRE>
you get an error:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; speed = raw_input(prompt)
But if the user types something other than a string of digits,
you get an error:
<PRE CLASS="verbatim">&gt;&gt;&gt; speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
What do you mean, an African or a European swallow?
&gt;&gt;&gt; int(speed)
&gt;&gt;&gt; int(speed)
ValueError: invalid literal for int()
ValueError: invalid literal for int()
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>We will see how to handle this kind of error later.</FONT></FONT></P><P><A NAME="@default408"></A><FONT COLOR=black><FONT SIZE=3>
</PRE>
</FONT></FONT><A NAME="@default409"></A></P><H2 CLASS="section"><A NAME="toc62"></A><A NAME="htoc69"><FONT COLOR=black><FONT SIZE=3>5.12</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;Debugging</FONT></FONT></H2><P><FONT COLOR=black><FONT SIZE=3>
We will see how to handle this kind of error later.
</FONT></FONT><A NAME="whitespace"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default410"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default411"></A></P><P><FONT COLOR=black><FONT SIZE=3>The traceback Python displays when an error occurs contains
 
=== 5.12&#XA0;&#XA0;Debugging ===
 
 
 
 
 
 
The traceback Python displays when an error occurs contains
a lot of information, but it can be overwhelming, especially
a lot of information, but it can be overwhelming, especially
when there are many frames on the stack. The most
when there are many frames on the stack. The most
useful parts are usually:</FONT></FONT></P><UL CLASS="itemize"><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>What kind of error it was, and</FONT></FONT></LI><LI CLASS="li-itemize"><FONT COLOR=black><FONT SIZE=3>Where it occurred.</FONT></FONT></LI></UL><P><FONT COLOR=black><FONT SIZE=3>Syntax errors are usually easy to find, but there are a few
useful parts are usually:
 
*What kind of error it was, and
 
*Where it occurred.
 
Syntax errors are usually easy to find, but there are a few
gotchas. Whitespace errors can be tricky because spaces and
gotchas. Whitespace errors can be tricky because spaces and
tabs are invisible and we are used to ignoring them.</FONT></FONT></P><P><A NAME="@default412"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>&gt;&gt;&gt; x = 5
tabs are invisible and we are used to ignoring them.
 
<PRE CLASS="verbatim">&gt;&gt;&gt; x = 5
&gt;&gt;&gt;  y = 6
&gt;&gt;&gt;  y = 6
   File "&lt;stdin&gt;", line 1
   File "&lt;stdin&gt;", line 1
Line 304: Line 478:
     ^
     ^
SyntaxError: invalid syntax
SyntaxError: invalid syntax
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>In this example, the problem is that the second line is indented by
</PRE>
one space. But the error message points to </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>y</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, which is
In this example, the problem is that the second line is indented by
one space. But the error message points to <TT>y</TT>, which is
misleading. In general, error messages indicate where the problem was
misleading. In general, error messages indicate where the problem was
discovered, but the actual error might be earlier in the code,
discovered, but the actual error might be earlier in the code,
sometimes on a previous line.</FONT></FONT></P><P><A NAME="@default413"></A><FONT COLOR=black><FONT SIZE=3>
sometimes on a previous line.
</FONT></FONT><A NAME="@default414"></A></P><P><FONT COLOR=black><FONT SIZE=3>The same is true of runtime errors. Suppose you are trying
 
 
 
 
The same is true of runtime errors. Suppose you are trying
to compute a signal-to-noise ratio in decibels. The formula
to compute a signal-to-noise ratio in decibels. The formula
is </FONT></FONT><FONT COLOR=black><FONT SIZE=3><I>SNR</I></FONT></FONT><SUB><FONT COLOR=black><FONT SIZE=3><I>db</I></FONT></FONT></SUB><FONT COLOR=black><FONT SIZE=3> = 10 </FONT></FONT><FONT COLOR=black><FONT SIZE=3>log</FONT></FONT><SUB><FONT COLOR=black><FONT SIZE=3>10</FONT></FONT></SUB><FONT COLOR=black><FONT SIZE=3> (<I>P</I></FONT></FONT><SUB><FONT COLOR=black><FONT SIZE=3><I>signal</I></FONT></FONT></SUB><FONT COLOR=black><FONT SIZE=3> / <I>P</I></FONT></FONT><SUB><FONT COLOR=black><FONT SIZE=3><I>noise</I></FONT></FONT></SUB><FONT COLOR=black><FONT SIZE=3>)</FONT></FONT><FONT COLOR=black><FONT SIZE=3>. In Python,
is <I>SNR</I><SUB><I>db</I></SUB> = 10 log<SUB>10</SUB> (<I>P</I><SUB><I>signal</I></SUB> / <I>P</I><SUB><I>noise</I></SUB>). In Python,
you might write something like this:</FONT></FONT></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>import math
you might write something like this:
<PRE CLASS="verbatim">import math
signal_power = 9
signal_power = 9
noise_power = 10
noise_power = 10
Line 318: Line 498:
decibels = 10 * math.log10(ratio)
decibels = 10 * math.log10(ratio)
print decibels
print decibels
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>But when you run it, you get an error message:</FONT></FONT></P><P><A NAME="@default415"></A><FONT COLOR=black><FONT SIZE=3>
</PRE>
</FONT></FONT><A NAME="@default416"></A></P><PRE CLASS="verbatim"><FONT COLOR=blue><FONT SIZE=4>Traceback (most recent call last):
But when you run it, you get an error message:
 
 
 
<PRE CLASS="verbatim">Traceback (most recent call last):
   File "snr.py", line 5, in ?
   File "snr.py", line 5, in ?
     decibels = 10 * math.log10(ratio)
     decibels = 10 * math.log10(ratio)
OverflowError: math range error
OverflowError: math range error
</FONT></FONT></PRE><P><FONT COLOR=black><FONT SIZE=3>The error message indicates line 5, but there is nothing
</PRE>
The error message indicates line 5, but there is nothing
wrong with that line. To find the real error, it might be
wrong with that line. To find the real error, it might be
useful to print the value of </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>ratio</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, which turns out to
useful to print the value of <TT>ratio</TT>, which turns out to
be 0. The problem is in line 4, because dividing two integers
be 0. The problem is in line 4, because dividing two integers
does floor division. The solution is to represent signal power
does floor division. The solution is to represent signal power
and noise power with floating-point values.</FONT></FONT></P><P><A NAME="@default417"></A><FONT COLOR=black><FONT SIZE=3>
and noise power with floating-point values.
</FONT></FONT><A NAME="@default418"></A></P><P><FONT COLOR=black><FONT SIZE=3>In general, error messages tell you where the problem was discovered,  
 
but that is often not where it was caused.</FONT></FONT></P><H2 CLASS="section"><A NAME="toc63"></A><A NAME="htoc70"><FONT COLOR=black><FONT SIZE=3>5.13</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>modulus operator:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> An operator, denoted with a percent sign
 
(</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>%</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>), that works on integers and yields the remainder when one
 
 
In general, error messages tell you where the problem was discovered,  
but that is often not where it was caused.
=== 5.13&#XA0;&#XA0;Glossary ===
 
<DL CLASS="description"><DT CLASS="dt-description">'''modulus operator:'''</DT><DD CLASS="dd-description"> An operator, denoted with a percent sign
(<TT>%</TT>), that works on integers and yields the remainder when one
number is divided by another.
number is divided by another.
</FONT></FONT><A NAME="@default419"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default420"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>boolean expression:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> An expression whose value is either  
</DD><DT CLASS="dt-description">'''boolean expression:'''</DT><DD CLASS="dd-description"> An expression whose value is either  
</FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>True</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3> or </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>False</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.
<TT>True</TT> or <TT>False</TT>.
</FONT></FONT><A NAME="@default421"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default422"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>comparison operator:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> One of the operators that compares
</DD><DT CLASS="dt-description">'''comparison operator:'''</DT><DD CLASS="dd-description"> One of the operators that compares
its operands: </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>==</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>!=</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>&gt;</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>&lt;</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>&gt;=</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>&lt;=</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>logical operator:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> One of the operators that combines boolean
its operands: <TT>==</TT>, <TT>!=</TT>, <TT>&gt;</TT>, <TT>&lt;</TT>, <TT>&gt;=</TT>, and <TT>&lt;=</TT>.</DD><DT CLASS="dt-description">'''logical operator:'''</DT><DD CLASS="dd-description"> One of the operators that combines boolean
expressions: </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>and</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>or</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>, and </FONT></FONT><FONT COLOR=black><FONT SIZE=3><TT>not</TT></FONT></FONT><FONT COLOR=black><FONT SIZE=3>.</FONT></FONT></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>conditional statement:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A statement that controls the flow of
expressions: <TT>and</TT>, <TT>or</TT>, and <TT>not</TT>.</DD><DT CLASS="dt-description">'''conditional statement:'''</DT><DD CLASS="dd-description"> A statement that controls the flow of
execution depending on some condition.
execution depending on some condition.
</FONT></FONT><A NAME="@default423"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default424"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>condition:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The boolean expression in a conditional statement
</DD><DT CLASS="dt-description">'''condition:'''</DT><DD CLASS="dd-description"> The boolean expression in a conditional statement
that determines which branch is executed.
that determines which branch is executed.
</FONT></FONT><A NAME="@default425"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>compound statement:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A statement that consists of a header
</DD><DT CLASS="dt-description">'''compound statement:'''</DT><DD CLASS="dd-description"> A statement that consists of a header
and a body. The header ends with a colon (:). The body is indented
and a body. The header ends with a colon (:). The body is indented
relative to the header.
relative to the header.
</FONT></FONT><A NAME="@default426"></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 within a compound statement.
</DD><DT CLASS="dt-description">'''body:'''</DT><DD CLASS="dd-description"> The sequence of statements within a compound statement.
</FONT></FONT><A NAME="@default427"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>branch:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> One of the alternative sequences of statements in
</DD><DT CLASS="dt-description">'''branch:'''</DT><DD CLASS="dd-description"> One of the alternative sequences of statements in
a conditional statement.
a conditional statement.
</FONT></FONT><A NAME="@default428"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>chained conditional:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A conditional statement with a series
</DD><DT CLASS="dt-description">'''chained conditional:'''</DT><DD CLASS="dd-description"> A conditional statement with a series
of alternative branches.
of alternative branches.
</FONT></FONT><A NAME="@default429"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default430"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>nested conditional:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A conditional statement that appears
</DD><DT CLASS="dt-description">'''nested conditional:'''</DT><DD CLASS="dd-description"> A conditional statement that appears
in one of the branches of another conditional statement.
in one of the branches of another conditional statement.
</FONT></FONT><A NAME="@default431"></A><FONT COLOR=black><FONT SIZE=3>
 
</FONT></FONT><A NAME="@default432"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>recursion:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> The process of calling the function that is
</DD><DT CLASS="dt-description">'''recursion:'''</DT><DD CLASS="dd-description"> The process of calling the function that is
currently executing.
currently executing.
</FONT></FONT><A NAME="@default433"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>base case:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A conditional branch in a
</DD><DT CLASS="dt-description">'''base case:'''</DT><DD CLASS="dd-description"> A conditional branch in a
recursive function that does not make a recursive call.
recursive function that does not make a recursive call.
</FONT></FONT><A NAME="@default434"></A></DD><DT CLASS="dt-description"><FONT COLOR=black><FONT SIZE=3><B>infinite recursion:</B></FONT></FONT></DT><DD CLASS="dd-description"><FONT COLOR=black><FONT SIZE=3> A function that calls itself recursively
</DD><DT CLASS="dt-description">'''infinite recursion:'''</DT><DD CLASS="dd-description"> A function that calls itself recursively
without ever reaching the base case. Eventually, an infinite recursion
without ever reaching the base case. Eventually, an infinite recursion
causes a runtime error.
causes a runtime error.
</FONT></FONT><A NAME="@default435"></A></DD></DL><H2 CLASS="section"><A NAME="toc64"></A><A NAME="htoc71"><FONT COLOR=black><FONT SIZE=3>5.14</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;1</B></FONT></FONT><FONT COLOR=black><FONT SIZE=3>&#XA0;&#XA0;<EM>
</DD></DL>=== 5.14&#XA0;&#XA0;Exercises ===
</EM></FONT></FONT><A NAME="@default436"></A><P><FONT COLOR=black><FONT SIZE=3><EM>Fermat&#X2019;s Last Theorem says that there are no integers
 
</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>a</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>, </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>b</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>, and </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>c</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> such that</EM></FONT></FONT></P><TABLE CLASS="display dcenter"><TR VALIGN="middle"><TD CLASS="dcell"><FONT COLOR=black><FONT SIZE=3><EM><I>a</I></EM></FONT></FONT><SUP><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></SUP><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;+&#XA0;<I>b</I></EM></FONT></FONT><SUP><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></SUP><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;=&#XA0;<I>c</I></EM></FONT></FONT><SUP><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></SUP><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;</EM></FONT></FONT></TD></TR>
<DIV CLASS="theorem">'''Exercise&#XA0;1'''&#XA0;&#XA0;''
</TABLE><P><FONT COLOR=black><FONT SIZE=3><EM>
''
for any values of </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> greater than 2.</EM></FONT></FONT></P><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function named </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>check_fermat</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> that takes four
''Fermat&#X2019;s Last Theorem says that there are no integers
parameters&#X2014;</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>a</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>, </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>b</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>, </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>c</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> and </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>n</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>&#X2014;and
''''<I>a</I>'''', ''''<I>b</I>'''', and ''''<I>c</I>'''' such that''
<TABLE CLASS="display dcenter"><TR VALIGN="middle"><TD CLASS="dcell">''<I>a</I>''<SUP>''<I>n</I>''</SUP>''&#XA0;+&#XA0;<I>b</I>''<SUP>''<I>n</I>''</SUP>''&#XA0;=&#XA0;<I>c</I>''<SUP>''<I>n</I>''</SUP>''&#XA0;''</TD></TR>
</TABLE>
''
for any values of ''''<I>n</I>'''' greater than 2.''
 
*''Write a function named ''<CODE>''check_fermat''</CODE>'' that takes four
parameters&#X2014;''''<TT>a</TT>'''', ''''<TT>b</TT>'''', ''''<TT>c</TT>'''' and ''''<TT>n</TT>''''&#X2014;and
that checks to see if Fermat&#X2019;s theorem holds. If
that checks to see if Fermat&#X2019;s theorem holds. If
</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> is greater than 2 and it turns out to be true that </EM></FONT></FONT><TABLE CLASS="display dcenter"><TR VALIGN="middle"><TD CLASS="dcell"><EM><FONT COLOR=black><FONT SIZE=3><EM><I>a</I></EM></FONT></FONT></EM><SUP><EM><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></EM></SUP><EM><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;+&#XA0;<I>b</I></EM></FONT></FONT></EM><SUP><EM><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></EM></SUP><EM><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;=&#XA0;<I>c</I></EM></FONT></FONT></EM><SUP><EM><FONT COLOR=black><FONT SIZE=3><EM><I>n</I></EM></FONT></FONT></EM></SUP><EM><FONT COLOR=black><FONT SIZE=3><EM>&#XA0;</EM></FONT></FONT></EM></TD></TR>
''''<I>n</I>'''' is greater than 2 and it turns out to be true that ''<TABLE CLASS="display dcenter"><TR VALIGN="middle"><TD CLASS="dcell">''''<I>a</I>''''<SUP>''''<I>n</I>''''</SUP>''''&#XA0;+&#XA0;<I>b</I>''''<SUP>''''<I>n</I>''''</SUP>''''&#XA0;=&#XA0;<I>c</I>''''<SUP>''''<I>n</I>''''</SUP>''''&#XA0;''''</TD></TR>
</TABLE><P><EM><FONT COLOR=black><FONT SIZE=3><EM>
</TABLE>
''''
the program should print, &#X201C;Holy smokes, Fermat was wrong!&#X201D;
the program should print, &#X201C;Holy smokes, Fermat was wrong!&#X201D;
Otherwise the program should print, &#X201C;No, that doesn&#X2019;t work.&#X201D;</EM></FONT></FONT></EM></P></LI><LI CLASS="li-enumerate"><EM><FONT COLOR=black><FONT SIZE=3><EM>Write a function that prompts the user to input values
Otherwise the program should print, &#X201C;No, that doesn&#X2019;t work.&#X201D;''''
for </EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM><TT>a</TT></EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM>, </EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM><TT>b</TT></EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM>, </EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM><TT>c</TT></EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM> and </EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM><TT>n</TT></EM></FONT></FONT></EM><EM><FONT COLOR=black><FONT SIZE=3><EM>, converts them to
 
integers, and uses </EM></FONT></FONT></EM><CODE><EM><FONT COLOR=black><FONT SIZE=3><EM>check_fermat</EM></FONT></FONT></EM></CODE><EM><FONT COLOR=black><FONT SIZE=3><EM> to check whether they
*''''Write a function that prompts the user to input values
violate Fermat&#X2019;s theorem.</EM></FONT></FONT></EM></LI></OL></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>
for ''''''''<TT>a</TT>'''''''', ''''''''<TT>b</TT>'''''''', ''''''''<TT>c</TT>'''''''' and ''''''''<TT>n</TT>'''''''', converts them to
</EM></FONT></FONT><A NAME="@default437"></A><P><FONT COLOR=black><FONT SIZE=3><EM>If you are given three sticks, you may or may not be able to arrange
integers, and uses ''''<CODE>''''check_fermat''''</CODE>'''' to check whether they
violate Fermat&#X2019;s theorem.''''
 
</DIV><DIV CLASS="theorem">'''Exercise&#XA0;2'''&#XA0;&#XA0;''
''
''If you are given three sticks, you may or may not be able to arrange
them in a triangle. For example, if one of the sticks is 12 inches
them in a triangle. For example, if one of the sticks is 12 inches
long and the other two are one inch long, it is clear that you will
long and the other two are one inch long, it is clear that you will
not be able to get the short sticks to meet in the middle. For any
not be able to get the short sticks to meet in the middle. For any
three lengths, there is a simple test to see if it is possible to form
three lengths, there is a simple test to see if it is possible to form
a triangle:</EM></FONT></FONT></P><BLOCKQUOTE CLASS="quotation"><FONT COLOR=black><FONT SIZE=3><EM>
a triangle:''
<BLOCKQUOTE CLASS="quotation">''
&#X201C;If any of the three lengths is greater than the sum of the other
&#X201C;If any of the three lengths is greater than the sum of the other
two, then you cannot form a triangle. Otherwise, you
two, then you cannot form a triangle. Otherwise, you
can</EM></FONT></FONT><SUP><A NAME="text8" HREF="#note8"><FONT COLOR=black><FONT SIZE=3><EM>2</EM></FONT></FONT></A></SUP><FONT COLOR=black><FONT SIZE=3><EM>.&#X201D;
can''<SUP>''2''</SUP>''.&#X201D;
</EM></FONT></FONT></BLOCKQUOTE><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function named </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>is_triangle</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> that takes three
''</BLOCKQUOTE>
 
*''Write a function named ''<CODE>''is_triangle''</CODE>'' that takes three
integers as arguments, and that prints either &#X201C;Yes&#X201D; or &#X201C;No,&#X201D; depending
integers as arguments, and that prints either &#X201C;Yes&#X201D; or &#X201C;No,&#X201D; depending
on whether you can or cannot form a triangle from sticks with the
on whether you can or cannot form a triangle from sticks with the
given lengths.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function that prompts the user to input three stick
given lengths.''
lengths, converts them to integers, and uses </EM></FONT></FONT><CODE><FONT COLOR=black><FONT SIZE=3><EM>is_triangle</EM></FONT></FONT></CODE><FONT COLOR=black><FONT SIZE=3><EM> to
 
check whether sticks with the given lengths can form a triangle.</EM></FONT></FONT></LI></OL></DIV><P><FONT COLOR=black><FONT SIZE=3>The following exercises use TurtleWorld from Chapter&#XA0;</FONT></FONT><A HREF="book005.html#turtlechap"><FONT COLOR=black><FONT SIZE=3>4</FONT></FONT></A><FONT COLOR=black><FONT SIZE=3>:</FONT></FONT></P><P><A NAME="@default438"></A></P><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><FONT COLOR=black><FONT SIZE=3><EM>Read the following function and see if you can figure out
*''Write a function that prompts the user to input three stick
what it does. Then run it (see the examples in Chapter&#XA0;</EM></FONT></FONT><A HREF="book005.html#turtlechap"><FONT COLOR=black><FONT SIZE=3><EM>4</EM></FONT></FONT></A><FONT COLOR=black><FONT SIZE=3><EM>).</EM></FONT></FONT></P><PRE CLASS="verbatim"><EM><FONT COLOR=blue><FONT SIZE=4>def draw(t, length, n):
lengths, converts them to integers, and uses ''<CODE>''is_triangle''</CODE>'' to
check whether sticks with the given lengths can form a triangle.''
 
</DIV>
The following exercises use TurtleWorld from Chapter&#XA0;4:
 
<DIV CLASS="theorem">'''Exercise&#XA0;3'''&#XA0;&#XA0;
''Read the following function and see if you can figure out
what it does. Then run it (see the examples in Chapter&#XA0;''''4'''').''
<PRE CLASS="verbatim">''def draw(t, length, n):
     if n == 0:
     if n == 0:
         return
         return
Line 403: Line 620:
     lt(t, angle)
     lt(t, angle)
     bk(t, length*n)
     bk(t, length*n)
</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;</FONT></FONT><P><A NAME="@default439"></A></P><P><FONT COLOR=black><FONT SIZE=3><EM>The Koch curve is a fractal that looks something like
''</PRE></DIV><DIV CLASS="theorem">'''Exercise&#XA0;4'''&#XA0;&#XA0;
this:</EM></FONT></FONT></P><DIV CLASS="center"><FONT COLOR=black><FONT SIZE=3><EM><IMG SRC="book008.png"></EM></FONT></FONT></DIV><P><FONT COLOR=black><FONT SIZE=3><EM>To draw a Koch curve with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>, all you have to do is</EM></FONT></FONT></P><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Draw a Koch curve with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I>/3</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Turn left 60 degrees.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Draw a Koch curve with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I>/3</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Turn right 120 degrees.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Draw a Koch curve with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I>/3</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Turn left 60 degrees.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Draw a Koch curve with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I>/3</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></LI></OL><P><FONT COLOR=black><FONT SIZE=3><EM>The only exception is if </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> is less than 3. In that case,
 
you can just draw a straight line with length </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><I>x</I></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></P><OL CLASS="enumerate" type=1><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function called </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>koch</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> that takes a turtle and
''The Koch curve is a fractal that looks something like
this:''
<DIV CLASS="center">''<IMG SRC="book008.png">''</DIV>
''To draw a Koch curve with length ''''<I>x</I>'''', all you have to do is''
 
*''Draw a Koch curve with length ''''<I>x</I>/3''''.''
 
*''Turn left 60 degrees.''
 
*''Draw a Koch curve with length ''''<I>x</I>/3''''.''
 
*''Turn right 120 degrees.''
 
*''Draw a Koch curve with length ''''<I>x</I>/3''''.''
 
*''Turn left 60 degrees.''
 
*''Draw a Koch curve with length ''''<I>x</I>/3''''.''
 
''The only exception is if ''''<I>x</I>'''' is less than 3. In that case,
you can just draw a straight line with length ''''<I>x</I>''''.''
 
*''Write a function called ''''<TT>koch</TT>'''' that takes a turtle and
a length as parameters, and that uses the turtle to draw a Koch
a length as parameters, and that uses the turtle to draw a Koch
curve with the given length.</EM></FONT></FONT></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>Write a function called </EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>snowflake</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> that draws three
curve with the given length.''
Koch curves to make the outline of a snowflake.</EM></FONT></FONT><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/koch.py</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM>.</EM></FONT></FONT></P></LI><LI CLASS="li-enumerate"><FONT COLOR=black><FONT SIZE=3><EM>The Koch curve can be generalized in several ways. See
 
</EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM><TT>wikipedia.org/wiki/Koch_snowflake</TT></EM></FONT></FONT><FONT COLOR=black><FONT SIZE=3><EM> for examples and
*''Write a function called ''''<TT>snowflake</TT>'''' that draws three
implement your favorite.</EM></FONT></FONT></LI></OL></DIV><HR CLASS="footnoterule"><DL CLASS="thefootnotes"><DT CLASS="dt-thefootnotes"><FONT COLOR=black><FONT SIZE=3>
Koch curves to make the outline of a snowflake.''
</FONT></FONT><A NAME="note7" HREF="#text7"><FONT COLOR=black><FONT SIZE=3>1</FONT></FONT></A></DT><DD CLASS="dd-thefootnotes"><FONT COLOR=black><FONT SIZE=3>In Python 3.0, this function is named
''You can see my solution at ''''<TT>thinkpython.com/code/koch.py</TT>''''.''
 
*''The Koch curve can be generalized in several ways. See
''''<TT>wikipedia.org/wiki/Koch_snowflake</TT>'''' for examples and
implement your favorite.''
 
</DIV><HR CLASS="footnoterule"><DL CLASS="thefootnotes"><DT CLASS="dt-thefootnotes">
1</DT><DD CLASS="dd-thefootnotes">In Python 3.0, this function is named
<TT>input</TT>
<TT>input</TT>
</FONT></FONT></DD><DT CLASS="dt-thefootnotes"><A NAME="note8" HREF="#text8"><FONT COLOR=black><FONT SIZE=3>2</FONT></FONT></A></DT><DD CLASS="dd-thefootnotes"><FONT COLOR=black><FONT SIZE=3>If the sum of two lengths equals the third, they form
</DD><DT CLASS="dt-thefootnotes">2</DT><DD CLASS="dd-thefootnotes">If the sum of two lengths equals the third, they form
what is called a &#X201C;degenerate&#X201D; triangle.
what is called a &#X201C;degenerate&#X201D; triangle.
</FONT></FONT></DD></DL>
</DD></DL>
<HR>
<HR>
<A HREF="book005.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="book007.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<IMG SRC="next_motif.gif" ALT="Next">
</BODY>
</HTML>

Latest revision as of 20:09, 18 May 2009

Chapter 5  Conditionals and recursion

5.1  Modulus operator

The modulus operator works on integers and yields the remainder when the first operand is divided by the second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators:

>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1

So 7 divided by 3 is 2 with 1 left over.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another—if x % y is zero, then x is divisible by y.

Also, you can extract the right-most digit or digits from a number. For example, x % 10 yields the right-most digit of x (in base 10). Similarly x % 100 yields the last two digits.

5.2  Boolean expressions

A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces True if they are equal and False otherwise:

>>> 5 == 5
True
>>> 5 == 6
False

True and False are special values that belong to the type bool; they are not strings:




>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>

The == operator is one of the comparison operators; the others are:

      x != y               # x is not equal to y
      x > y                # x is greater than y
      x < y                # x is less than y
      x >= y               # x is greater than or equal to y
      x <= y               # x is less than or equal to y

Although these operations are probably familiar to you, the Python symbols are different from the mathematical symbols. A common error is to use a single equal sign (=) instead of a double equal sign (==). Remember that = is an assignment operator and == is a comparison operator. There is no such thing as =< or =>.


5.3  Logical operators

There are three logical operators: and, or, and not. The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and less than 10.





n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.

Finally, the not operator negates a boolean expression, so not (x > y) is true if x > y is false, that is, if x is less than or equal to y.

Strictly speaking, the operands of the logical operators should be boolean expressions, but Python is not very strict. Any nonzero number is interpreted as “true.”

>>> 17 and True
True

This flexibility can be useful, but there are some subtleties to it that might be confusing. You might want to avoid it (unless you know what you are doing).

5.4  Conditional execution

In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

if x > 0:
    print 'x is positive'

The boolean expression after the if statement is called the condition. If it is true, then the indented statement gets executed. If not, nothing happens.



if statements have the same structure as function definitions: a header followed by an indented block. Statements like this are called compound statements.

There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements (usually as a place keeper for code you haven’t written yet). In that case, you can use the pass statement, which does nothing.


if x < 0:
    pass          # need to handle negative values!

=== 5.5  Alternative execution ===





A second form of the if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this:

if x%2 == 0:
    print 'x is even'
else:
    print 'x is odd'

If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution.

5.6  Chained conditionals

Sometimes there are more than two possibilities and we need more than two branches. One way to express a computation like that is a chained conditional:

if x < y:
    print 'x is less than y'
elif x > y:
    print 'x is greater than y'
else:
    print 'x and y are equal'

elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.


if choice == 'a':
    draw_a()
elif choice == 'b':
    draw_b()
elif choice == 'c':
    draw_c()

Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes.

5.7  Nested conditionals

One conditional can also be nested within another. We could have written the trichotomy example like this:

if x == y:
    print 'x and y are equal'
else:
    if x < y:
        print 'x is less than y'
    else:
        print 'x is greater than y'

The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.

Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.

Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:

if 0 < x:
    if x < 10:
        print 'x is a positive single-digit number.'

The print statement is executed only if we make it past both conditionals, so we can get the same effect with the and operator:

if 0 < x and x < 10:
    print 'x is a positive single-digit number.'

=== 5.8  Recursion ===



It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function:

def countdown(n):
    if n <= 0:
        print 'Blastoff!'
    else:
        print n
        countdown(n-1)

If n is 0 or negative, it outputs the word, “Blastoff!” Otherwise, it outputs n and then calls a function named countdown—itself—passing n-1 as an argument.

What happens if we call this function like this?

>>> countdown(3)

The execution of countdown begins with n=3, and since n is greater than 0, it outputs the value 3, and then calls itself...

The execution of countdown begins with n=2, and since

n is greater than 0, it outputs the value 2, and then calls itself...

The execution of countdown begins with n=1, and since

n is greater than 0, it outputs the value 1, and then calls itself...

The execution of countdown begins with n=0, and since n is not greater than 0, it outputs the word, “Blastoff!” and then returns.

The countdown that got n=1 returns.

The countdown that got n=2 returns.

The countdown that got n=3 returns.

And then you’re back in __main__. So, the total output looks like this:

3
2
1
Blastoff!

A function that calls itself is recursive; the process is called recursion.



As another example, we can write a function that prints a string n times.

def print_n(s, n):
    if n <= 0:
        return
    print s
    print_n(s, n-1)

If n <= 0 the return statement exits the function. The flow of execution immediately returns to the caller, and the remaining lines of the function are not executed.



The rest of the function is similar to countdown: if n is greater than 0, it displays s and then calls itself to display s n−1 additional times. So the number of lines of output is 1 + (n - 1), which adds up to n.

For simple examples like this, it is probably easier to use a for loop. But we will see examples later that are hard to write with a for loop and easy to write with recursion, so it is good to start early.

5.9  Stack diagrams for recursive functions

In Section 3.10, we used a stack diagram to represent the state of a program during a function call. The same kind of diagram can help interpret a recursive function.

Every time a function gets called, Python creates a new function frame, which contains the function’s local variables and parameters. For a recursive function, there might be more than one frame on the stack at the same time.

This figure shows a stack diagram for countdown called with n = 3:

<IMG SRC="book007.png">

As usual, the top of the stack is the frame for __main__. It is empty because we did not create any variables in __main__ or pass any arguments to it.



The four countdown frames have different values for the parameter n. The bottom of the stack, where n=0, is called the base case. It does not make a recursive call, so there are no more frames.

Draw a stack diagram for print_n called with s = 'Hello' and n=2.

Write a function called do_n that takes a function object and a number, n as arguments, and that calls the given function n times.

=== 5.10  Infinite recursion ===





If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. Here is a minimal program with an infinite recursion:

def recurse():
    recurse()

In most programming environments, a program with infinite recursion does not really run forever. Python reports an error message when the maximum recursion depth is reached:


  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
  File "<stdin>", line 2, in recurse
                  .   
                  .
                  .
  File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded

This traceback is a little bigger than the one we saw in the previous chapter. When the error occurs, there are 1000 recurse frames on the stack!

5.11  Keyboard input

The programs we have written so far are a bit rude in the sense that they accept no input from the user. They just do the same thing every time.

Python provides a built-in function called raw_input that gets input from the keyboard1. When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and raw_input returns what the user typed as a string.



>>> input = raw_input()
What are you waiting for?
>>> print input
What are you waiting for?

Before getting input from the user, it is a good idea to print a prompt telling the user what to input. raw_input can take a prompt as an argument:

>>> name = raw_input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!

The sequence \n at the end of the prompt represents a newline, which is a special character that causes a line break. That’s why the user’s input appears below the prompt.

If you expect the user to type an integer, you can try to convert the return value to int:

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17

But if the user types something other than a string of digits, you get an error:

>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()

We will see how to handle this kind of error later.


5.12  Debugging

The traceback Python displays when an error occurs contains a lot of information, but it can be overwhelming, especially when there are many frames on the stack. The most useful parts are usually:

  • What kind of error it was, and
  • Where it occurred.

Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.

>>> x = 5
>>>  y = 6
  File "<stdin>", line 1
    y = 6
    ^
SyntaxError: invalid syntax

In this example, the problem is that the second line is indented by one space. But the error message points to y, which is misleading. In general, error messages indicate where the problem was discovered, but the actual error might be earlier in the code, sometimes on a previous line.



The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio in decibels. The formula is SNRdb = 10 log10 (Psignal / Pnoise). In Python, you might write something like this:

import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels

But when you run it, you get an error message:


Traceback (most recent call last):
  File "snr.py", line 5, in ?
    decibels = 10 * math.log10(ratio)
OverflowError: math range error

The error message indicates line 5, but there is nothing wrong with that line. To find the real error, it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4, because dividing two integers does floor division. The solution is to represent signal power and noise power with floating-point values.



In general, error messages tell you where the problem was discovered, but that is often not where it was caused.

5.13  Glossary

modulus operator:
An operator, denoted with a percent sign (%), that works on integers and yields the remainder when one number is divided by another.
boolean expression:
An expression whose value is either True or False.
comparison operator:
One of the operators that compares its operands: ==, !=, >, <, >=, and <=.
logical operator:
One of the operators that combines boolean expressions: and, or, and not.
conditional statement:
A statement that controls the flow of execution depending on some condition.
condition:
The boolean expression in a conditional statement that determines which branch is executed.
compound statement:
A statement that consists of a header and a body. The header ends with a colon (:). The body is indented relative to the header.
body:
The sequence of statements within a compound statement.
branch:
One of the alternative sequences of statements in a conditional statement.
chained conditional:
A conditional statement with a series of alternative branches.
nested conditional:
A conditional statement that appears in one of the branches of another conditional statement.
recursion:
The process of calling the function that is currently executing.
base case:
A conditional branch in a recursive function that does not make a recursive call.
infinite recursion:
A function that calls itself recursively without ever reaching the base case. Eventually, an infinite recursion causes a runtime error.

=== 5.14  Exercises ===

Exercise 1  

Fermat’s Last Theorem says that there are no integers 'a', 'b', and 'c' such that

an + bn = cn 

for any values of 'n' greater than 2.

  • Write a function named check_fermat that takes four

parameters—'a', 'b', 'c' and 'n'—and that checks to see if Fermat’s theorem holds. If

'n' is greater than 2 and it turns out to be true that
'a''n'' + b''n'' = c''n'' '

' the program should print, “Holy smokes, Fermat was wrong!” Otherwise the program should print, “No, that doesn’t work.”'

  • 'Write a function that prompts the user to input values

for '''a''', '''b''', '''c''' and '''n''', converts them to integers, and uses ''check_fermat'' to check whether they violate Fermat’s theorem.'

Exercise 2  

If you are given three sticks, you may or may not be able to arrange them in a triangle. For example, if one of the sticks is 12 inches long and the other two are one inch long, it is clear that you will not be able to get the short sticks to meet in the middle. For any three lengths, there is a simple test to see if it is possible to form a triangle:

“If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can2.”

  • Write a function named is_triangle that takes three

integers as arguments, and that prints either “Yes” or “No,” depending on whether you can or cannot form a triangle from sticks with the given lengths.

  • Write a function that prompts the user to input three stick

lengths, converts them to integers, and uses is_triangle to check whether sticks with the given lengths can form a triangle.

The following exercises use TurtleWorld from Chapter 4:

Exercise 3  

Read the following function and see if you can figure out what it does. Then run it (see the examples in Chapter '4').

''def draw(t, length, n):
    if n == 0:
        return
    angle = 50
    fd(t, length*n)
    lt(t, angle)
    draw(t, length, n-1)
    rt(t, 2*angle)
    draw(t, length, n-1)
    lt(t, angle)
    bk(t, length*n)
''
Exercise 4  

The Koch curve is a fractal that looks something like this:

<IMG SRC="book008.png">

To draw a Koch curve with length 'x', all you have to do is

  • Draw a Koch curve with length 'x/3'.
  • Turn left 60 degrees.
  • Draw a Koch curve with length 'x/3'.
  • Turn right 120 degrees.
  • Draw a Koch curve with length 'x/3'.
  • Turn left 60 degrees.
  • Draw a Koch curve with length 'x/3'.

The only exception is if 'x' is less than 3. In that case, you can just draw a straight line with length 'x'.

  • Write a function called 'koch' that takes a turtle and

a length as parameters, and that uses the turtle to draw a Koch curve with the given length.

  • Write a function called 'snowflake' that draws three

Koch curves to make the outline of a snowflake. You can see my solution at 'thinkpython.com/code/koch.py'.

  • The Koch curve can be generalized in several ways. See

'wikipedia.org/wiki/Koch_snowflake' for examples and implement your favorite.


1
In Python 3.0, this function is named input
2
If the sum of two lengths equals the third, they form what is called a “degenerate” triangle.

<IMG SRC="previous_motif.gif" ALT="Previous"> <IMG SRC="contents_motif.gif" ALT="Up"> <IMG SRC="next_motif.gif" ALT="Next">