Think Python/Conditional and recursion

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

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 <TT>False</TT> otherwise: <TT>True</TT> and <TT>False</TT> are special values that belong to the type <TT>bool</TT>; they are not strings:

The <TT>==</TT> operator is one of the comparison operators; the others are: 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 (<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>=&lt;</TT> or <TT>=></TT>.

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, <TT>x > 0 and x &lt; 10</TT> is true only if <TT>x</TT> is greater than 0 and less than 10.

<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. Any nonzero number is interpreted as “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).

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 <TT>if</TT> statement:

The boolean expression after the <TT>if</TT> statement is 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 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 <TT>pass</TT> statement, which does nothing.

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

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

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: <TT>elif</TT> is an abbreviation of “else if.” Again, exactly 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.

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.

Nested conditionals
One conditional can also be nested within another. We could have written the trichotomy example like this: The outer conditional contains two branches. The first branch contains a simple statement. The second branch contains another <TT>if</TT> 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: 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:

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

What happens if we call this function like this? The execution of <TT>countdown</TT> begins with <TT>n=3</TT>, and since <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. </BLOCKQUOTE> The <TT>countdown</TT> that got <TT>n=1</TT> returns.

</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. So, the total output looks like this: A function that calls itself is recursive; the process is called recursion.

As another example, we can write a function that prints a string <TT>n</TT> times. 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 lines of the function are not executed.

The rest of the function is similar to <TT>countdown</TT>: if <TT>n</TT> is greater than 0, it displays <TT>s</TT> and then calls itself to display <TT>s</TT> n−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.

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 <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. It is empty because we did not create any variables in  or pass any arguments to it.

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 there are no more frames. <BLOCKQUOTE CLASS="quote"> Draw a stack diagram for  called with and <TT>n=2</TT>. </BLOCKQUOTE><BLOCKQUOTE CLASS="quote"> Write a function called  that takes a function object and a number, <TT>n</TT> as arguments, and that calls the given function <TT>n</TT> times. </BLOCKQUOTE>

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

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

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  that gets input from the keyboard. 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 returns what the user typed as a string.

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

The sequence  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 <TT>int</TT>: But if the user types something other than a string of digits, you get an error: We will see how to handle this kind of error later.

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.

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 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 SNR<SUB>db</SUB> = 10 log<SUB>10</SUB> (P<SUB>signal</SUB> / P<SUB>noise</SUB>). In Python, you might write something like this: But when you run it, you get an error message:

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 <TT>ratio</TT>, 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.

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.

</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: <TT>==</TT>, <TT>!=</TT>, <TT>></TT>, <TT>&lt;</TT>, <TT>>=</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: <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.

</DD><DT CLASS="dt-description">condition:</DT><DD CLASS="dd-description"> The boolean expression in a conditional statement 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 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. </DD><DT CLASS="dt-description">chained conditional:</DT><DD CLASS="dd-description"> A conditional statement with a series 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.

</DD><DT CLASS="dt-description">recursion:</DT><DD CLASS="dd-description"> The process of calling the function that is 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. </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 causes a runtime error. </DD></DL>

Exercises
Exercise 1

Fermat's Last Theorem says that there are no integers a, b, and c such that  for any values of n greater than 2.
 * Write a function named  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 n is greater than 2 and it turns out to be true that   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 <TT>a</TT>, <TT>b</TT>, <TT>c</TT> and <TT>n</TT>, converts them to integers, and uses  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:''

<BLOCKQUOTE CLASS="quotation">''&#X201C;If any of the three lengths is greater than the sum of the other two, then you cannot form a triangle. Otherwise, you can. &#X201D;''</BLOCKQUOTE>


 * Write a function named   that takes three 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 given lengths.
 * Write a function that prompts the user to input three stick lengths, converts them to integers, and uses   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').''

<DIV CLASS="theorem">Exercise 4

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 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 <TT>koch</TT> 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 '<TT>snowflake</TT>' that draws three 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.