Archive:Think Python/Conditional and recursion: Difference between revisions
wikademia>Whiteknight m Think Python: Automatically uploading HTML source of this book from http://www.greenteapress.com/thinkpython/html/. Will convert to wikitext in a separate step |
wikademia>Whiteknight m Partial (mostly) conversion from HTML to Wikitext |
||
| Line 1: | Line 1: | ||
{{Think Python/Page}} | |||
== 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 | when the first operand is divided by the second. In Python, the | ||
modulus operator is a percent sign ( | modulus operator is a percent sign (<CODE>%</CODE>). The syntax is the same | ||
as for other operators: | as for other operators: | ||
<PRE CLASS="verbatim">>>> quotient = 7 / 3 | |||
>>> print quotient | >>> print quotient | ||
2 | 2 | ||
| Line 24: | Line 18: | ||
>>> print remainder | >>> print remainder | ||
1 | 1 | ||
</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—if | example, you can check whether one number is divisible by another—if | ||
<TT>x % y</TT> is zero, then <TT>x</TT> is divisible by <TT>y</TT>. | |||
or digits from a number. For example, | |||
right-most digit of | Also, you can extract the right-most digit | ||
yields the last two digits. | or digits from a number. For example, <TT>x % 10</TT> yields the | ||
right-most digit of <TT>x</TT> (in base 10). Similarly <TT>x % 100</TT> | |||
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 | or false. The following examples use the | ||
operator | operator <TT>==</TT>, which compares two operands and produces | ||
<TT>True</TT> if they are equal and <TT>False</TT> otherwise: | |||
<PRE CLASS="verbatim">>>> 5 == 5 | |||
True | True | ||
>>> 5 == 6 | >>> 5 == 6 | ||
False | False | ||
</PRE> | |||
values that belong to the type | <TT>True</TT> and <TT>False</TT> are special | ||
values that belong to the type <TT>bool</TT>; they are not strings: | |||
<PRE CLASS="verbatim">>>> type(True) | |||
<type 'bool'> | <type 'bool'> | ||
>>> type(False) | >>> type(False) | ||
<type 'bool'> | <type 'bool'> | ||
</PRE> | |||
others are: | 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 > y # x is greater than y | x > y # x is greater than y | ||
x < y # x is less than y | x < y # x is less than y | ||
x >= y # x is greater than or equal to y | x >= y # x is greater than or equal to y | ||
x <= y # x is less than or equal to y | x <= y # x is less than or equal to y | ||
</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 ( | is to use a single equal sign (<TT>=</TT>) instead of a double equal sign | ||
( | (<TT>==</TT>). Remember that <TT>=</TT> is an assignment operator and | ||
<TT>==</TT> is a comparison operator. There is no such thing as | |||
<TT>=<</TT> or <TT>=></TT>. | |||
=== 5.3  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, | ||
<TT>x > 0 and x < 10</TT> is true only if <TT>x</TT> is greater than 0 | |||
''and'' less than 10. | |||
is true, that is, if the number is divisible by 2 | |||
expression, so | |||
that is, if | |||
<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 > y)</TT> is true if <TT>x > 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 “true.” | Any nonzero number is interpreted as “true.” | ||
<PRE CLASS="verbatim">>>> 17 and True | |||
True | True | ||
</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). | 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 | to check conditions and change the behavior of the program | ||
accordingly. | accordingly. '''Conditional statements''' give us this ability. The | ||
simplest form is the | simplest form is the <TT>if</TT> statement: | ||
<PRE CLASS="verbatim">if x > 0: | |||
print 'x is positive' | print 'x is positive' | ||
</PRE> | |||
called the | The boolean expression after the <TT>if</TT> statement is | ||
statement gets executed. If not, nothing happens. | called the '''condition'''. If it is true, then the indented | ||
statement gets executed. If not, nothing happens. | |||
<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 | 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’t written yet). In that | as a place keeper for code you haven’t written yet). In that | ||
case, you can use the | case, you can use the <TT>pass</TT> statement, which does nothing. | ||
<PRE CLASS="verbatim">if x < 0: | |||
pass # need to handle negative values! | pass # need to handle negative values! | ||
</PRE>=== 5.5  Alternative execution === | |||
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: | 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' | ||
</PRE> | |||
know 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 | ||
'''branches''', because they are branches in the flow of execution. | |||
=== 5.6  Chained conditionals === | |||
two branches. One way to express a computation like that is a | |||
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 < y: | |||
print 'x is less than y' | print 'x is less than y' | ||
elif x > y: | elif x > y: | ||
| Line 127: | Line 189: | ||
else: | else: | ||
print 'x and y are equal' | print 'x and y are equal' | ||
</PRE> | |||
branch will be executed. There is no limit on the number of | <TT>elif</TT> is an abbreviation of “else if.” Again, exactly one | ||
at the end, but there doesn’t have to be one. | 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 | ||
at the end, but there doesn’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() | ||
</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. | first true branch executes. | ||
=== 5.7  Nested conditionals === | |||
written the trichotomy example like this: | |||
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' | ||
</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 | 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. | although they could have been conditional statements as well. | ||
apparent, | |||
quickly. In general, it is a good idea to avoid them when you can. | 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: | single conditional: | ||
<PRE CLASS="verbatim">if 0 < x: | |||
if x < 10: | if x < 10: | ||
print 'x is a positive single-digit number.' | print 'x is a positive single-digit number.' | ||
</PRE> | |||
conditionals, so we can get the same effect with the | 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 < x and x < 10: | |||
print 'x is a positive single-digit number.' | print 'x is a positive single-digit number.' | ||
</PRE>=== 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 | 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: | For example, look at the following function: | ||
<PRE CLASS="verbatim">def countdown(n): | |||
if n <= 0: | if n <= 0: | ||
print 'Blastoff!' | print 'Blastoff!' | ||
| Line 176: | Line 262: | ||
print n | print n | ||
countdown(n-1) | countdown(n-1) | ||
</PRE> | |||
Otherwise, it outputs | If <TT>n</TT> is 0 or negative, it outputs the word, “Blastoff!” | ||
Otherwise, it outputs <TT>n</TT> and then calls a function named <TT>countdown</TT>—itself—passing <TT>n-1</TT> as an argument. | |||
The execution of | What happens if we call this function like this? | ||
<PRE CLASS="verbatim">>>> countdown(3) | |||
The execution of | </PRE> | ||
The execution of <TT>countdown</TT> begins with <TT>n=3</TT>, and since | |||
The execution of | <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, “Blastoff!” and then | |||
returns. | returns. | ||
</BLOCKQUOTE> | |||
The <TT>countdown</TT> that got <TT>n=1</TT> returns. | |||
total output looks like this: | </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’re back in <CODE>__main__</CODE>. So, the | |||
total output looks like this: | |||
<PRE CLASS="verbatim">3 | |||
2 | 2 | ||
1 | 1 | ||
Blastoff! | Blastoff! | ||
</PRE> | |||
called | A function that calls itself is '''recursive'''; the process is | ||
called '''recursion'''. | |||
string | |||
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 <= 0: | if n <= 0: | ||
return | return | ||
print s | print s | ||
print_n(s, n-1) | print_n(s, n-1) | ||
</PRE> | |||
If <TT>n <= 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. | lines of the function are not executed. | ||
greater than 0, it displays | |||
is | |||
The rest of the function is similar to <TT>countdown</TT>: if <TT>n</TT> is | |||
with a | greater than 0, it displays <TT>s</TT> and then calls itself to display | ||
good to start early. | <TT>s</TT> <I>n</I>−1 additional times. So the number of lines of output | ||
is <TT>1 + (n - 1)</TT>, which adds up to | |||
<TT>n</TT>. | |||
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  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 | the state of a program during a function call. The same kind of | ||
diagram can help interpret a recursive function. | 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. | frame, which contains the function’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. | stack at the same time. | ||
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 | ||
<CODE>__main__</CODE> or pass any arguments to it. | |||
parameter | |||
called the | |||
there are no more frames. | |||
Draw a stack diagram for | The four <TT>countdown</TT> frames have different values for the | ||
parameter <TT>n</TT>. The bottom of the stack, where <TT>n=0</TT>, is | |||
called the '''base case'''. It does not make a recursive call, so | |||
Write a function called | there are no more frames. | ||
object and a number, | <BLOCKQUOTE CLASS="quote"> | ||
the given function | Draw a stack diagram for <CODE>print_n</CODE> called with | ||
<CODE>s = 'Hello'</CODE> and <TT>n=2</TT>. | |||
</BLOCKQUOTE><BLOCKQUOTE CLASS="quote"> | |||
Write a function called <CODE>do_n</CODE> that takes a function | |||
object and a number, <TT>n</TT> as arguments, and that calls | |||
the given function <TT>n</TT> times. | |||
</BLOCKQUOTE>=== 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 | recursive calls forever, and the program never terminates. This is | ||
known as | known as '''infinite recursion''', and it is generally not | ||
a good idea. Here is a minimal program with an infinite recursion: | a good idea. Here is a minimal program with an infinite recursion: | ||
<PRE CLASS="verbatim">def recurse(): | |||
recurse() | recurse() | ||
</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: | message when the maximum recursion depth is reached: | ||
<PRE CLASS="verbatim"> File "<stdin>", line 2, in recurse | |||
File "<stdin>", line 2, in recurse | File "<stdin>", line 2, in recurse | ||
File "<stdin>", line 2, in recurse | File "<stdin>", line 2, in recurse | ||
| Line 253: | Line 391: | ||
File "<stdin>", line 2, in recurse | File "<stdin>", line 2, in recurse | ||
RuntimeError: Maximum recursion depth exceeded | RuntimeError: Maximum recursion depth exceeded | ||
</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 | ||
<TT>recurse</TT> 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 | they accept no input from the user. They just do the same thing every | ||
time. | time. | ||
input from the keyboard | |||
waits for the user to type something. When the user presses | Python provides a built-in function called <CODE>raw_input</CODE> that gets | ||
returns what the user typed as a string. | input from the keyboard<SUP>1</SUP>. 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 <CODE>raw_input</CODE> | |||
returns what the user typed as a string. | |||
<PRE CLASS="verbatim">>>> input = raw_input() | |||
What are you waiting for? | What are you waiting for? | ||
>>> print input | >>> print input | ||
What are you waiting for? | What are you waiting for? | ||
</PRE> | |||
prompt telling the user what to input. | Before getting input from the user, it is a good idea to print a | ||
prompt as an argument: | prompt telling the user what to input. <CODE>raw_input</CODE> can take a | ||
prompt as an argument: | |||
<PRE CLASS="verbatim">>>> 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! | ||
>>> print name | >>> print name | ||
Arthur, King of the Britons! | Arthur, King of the Britons! | ||
</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’s why the user’s input appears below the prompt. | That’s why the user’s input appears below the prompt. | ||
the return value to | |||
If you expect the user to type an integer, you can try to convert | |||
the return value to <TT>int</TT>: | |||
<PRE CLASS="verbatim">>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n' | |||
>>> speed = raw_input(prompt) | >>> 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: | ||
>>> int(speed) | >>> int(speed) | ||
17 | 17 | ||
</PRE> | |||
you get an error: | But if the user types something other than a string of digits, | ||
you get an error: | |||
<PRE CLASS="verbatim">>>> 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? | ||
>>> int(speed) | >>> int(speed) | ||
ValueError: invalid literal for int() | ValueError: invalid literal for int() | ||
</PRE> | |||
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 | 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: | 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. | tabs are invisible and we are used to ignoring them. | ||
<PRE CLASS="verbatim">>>> x = 5 | |||
>>> y = 6 | >>> y = 6 | ||
File "<stdin>", line 1 | File "<stdin>", line 1 | ||
| Line 304: | Line 478: | ||
^ | ^ | ||
SyntaxError: invalid syntax | SyntaxError: invalid syntax | ||
</PRE> | |||
one space. But the error message points to | 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. | 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 | to compute a signal-to-noise ratio in decibels. The formula | ||
is | 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: | 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 | ||
</PRE> | |||
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 | ||
</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 | 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. | and noise power with floating-point values. | ||
but that is often not where it was caused. | |||
( | |||
In general, error messages tell you where the problem was discovered, | |||
but that is often not where it was caused. | |||
=== 5.13  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. | ||
</DD><DT CLASS="dt-description">'''boolean expression:'''</DT><DD CLASS="dd-description"> An expression whose value is either | |||
<TT>True</TT> or <TT>False</TT>. | |||
</DD><DT CLASS="dt-description">'''comparison operator:'''</DT><DD CLASS="dd-description"> One of the operators that compares | |||
its operands: | its operands: <TT>==</TT>, <TT>!=</TT>, <TT>></TT>, <TT><</TT>, <TT>>=</TT>, and <TT><=</TT>.</DD><DT CLASS="dt-description">'''logical operator:'''</DT><DD CLASS="dd-description"> One of the operators that combines boolean | ||
expressions: | 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. | ||
</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. | ||
</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. | ||
</DD><DT CLASS="dt-description">'''body:'''</DT><DD CLASS="dd-description"> The sequence of statements within a compound statement. | |||
</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. | ||
</DD><DT CLASS="dt-description">'''chained conditional:'''</DT><DD CLASS="dd-description"> A conditional statement with a series | |||
of alternative branches. | of alternative branches. | ||
</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. | ||
</DD><DT CLASS="dt-description">'''recursion:'''</DT><DD CLASS="dd-description"> The process of calling the function that is | |||
currently executing. | currently executing. | ||
</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. | ||
</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. | ||
</DD></DL>=== 5.14  Exercises === | |||
<DIV CLASS="theorem">'''Exercise 1'''  '' | |||
</TABLE> | '' | ||
for any values of | ''Fermat’s Last Theorem says that there are no integers | ||
parameters— | ''''<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>'' + <I>b</I>''<SUP>''<I>n</I>''</SUP>'' = <I>c</I>''<SUP>''<I>n</I>''</SUP>'' ''</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—''''<TT>a</TT>'''', ''''<TT>b</TT>'''', ''''<TT>c</TT>'''' and ''''<TT>n</TT>''''—and | |||
that checks to see if Fermat’s theorem holds. If | that checks to see if Fermat’s theorem holds. If | ||
''''<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>'''' + <I>b</I>''''<SUP>''''<I>n</I>''''</SUP>'''' = <I>c</I>''''<SUP>''''<I>n</I>''''</SUP>'''' ''''</TD></TR> | |||
</TABLE> | </TABLE> | ||
'''' | |||
the program should print, “Holy smokes, Fermat was wrong!” | the program should print, “Holy smokes, Fermat was wrong!” | ||
Otherwise the program should print, “No, that doesn’t work.” | Otherwise the program should print, “No, that doesn’t work.”'''' | ||
for | |||
integers, and uses | *''''Write a function that prompts the user to input values | ||
violate Fermat’s theorem. | for ''''''''<TT>a</TT>'''''''', ''''''''<TT>b</TT>'''''''', ''''''''<TT>c</TT>'''''''' and ''''''''<TT>n</TT>'''''''', converts them to | ||
integers, and uses ''''<CODE>''''check_fermat''''</CODE>'''' to check whether they | |||
violate Fermat’s theorem.'''' | |||
</DIV><DIV CLASS="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 | 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: | a triangle:'' | ||
<BLOCKQUOTE CLASS="quotation">'' | |||
“If any of the three lengths is greater than the sum of the other | “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 | can''<SUP>''2''</SUP>''.” | ||
''</BLOCKQUOTE> | |||
*''Write a function named ''<CODE>''is_triangle''</CODE>'' that takes three | |||
integers as arguments, and that prints either “Yes” or “No,” depending | integers as arguments, and that prints either “Yes” or “No,” 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. | given lengths.'' | ||
lengths, converts them to integers, and uses | |||
check whether sticks with the given lengths can form a triangle. | *''Write a function that prompts the user to input three stick | ||
what it does. Then run it (see the examples in Chapter  | 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 4: | |||
<DIV CLASS="theorem">'''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'''').'' | |||
<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) | ||
''</PRE></DIV><DIV CLASS="theorem">'''Exercise 4'''   | |||
this: | |||
you can just draw a straight line with length | ''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. | curve with the given length.'' | ||
Koch curves to make the outline of a snowflake. | |||
*''Write a function called ''''<TT>snowflake</TT>'''' that draws three | |||
implement your favorite. | Koch curves to make the outline of a snowflake.'' | ||
''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> | ||
</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 “degenerate” triangle. | what is called a “degenerate” triangle. | ||
</DD></DL> | |||
<HR> | <HR> | ||
<IMG SRC="previous_motif.gif" ALT="Previous"> | |||
<IMG SRC="contents_motif.gif" ALT="Up"> | |||
<IMG SRC="next_motif.gif" ALT="Next"> | |||
Revision as of 23:09, 15 September 2008
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:
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_ncalled withs = 'Hello'and n=2.
Write a function called
do_nthat 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 ===
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_fermatthat 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.'
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_trianglethat 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:
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)
''The Koch curve is a fractal that looks something like this:
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">