How to Think Like a Computer Scientist: Learning with Python 2nd Edition/Conditionals

= Conditionals =

The modulus operator
The modulus operator works on integers (and integer expressions) 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 values and expressions
The Python type for storing true and false values is called bool, named after the British mathematician, George Boole. George Boole created Boolean algebra, which is the basis of all modern computer arithmetic.

There are only two boolean values: <tt>True</tt> and <tt>False</tt>. Capitalization is important, since <tt>true</tt> and <tt>false</tt> are not boolean values.

A boolean expression is an expression that evaluates to a boolean value. The operator <tt>==</tt> compares two values and produces a boolean value:

In the first statement, the two operands are equal, so the expression evaluates to <tt>True</tt>; in the second statement, 5 is not equal to 6, so we get <tt>False</tt>.

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. Also, there is no such thing as <tt>=&lt;</tt> or <tt>=&gt;</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 &gt; 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 &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>.

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.

The syntax for an <tt>if</tt> statement looks like this:

As with the function definition from last chapter and other compound statements, the <tt>if</tt> statement consists of a header and a body. The header begins with the keyword <tt>if</tt> followed by a boolean expression and ends with a colon.

The indented statements that follow are called a block. The first unindented statement marks the end of the block. A statement block inside a compound statement is called the body of the statement.

Each of the statements inside the body are executed in order if the boolean expression evaluates to <tt>True</tt>. The entire block is skipped if the boolean expression evaluates to <tt>False</tt>.

There is no limit on the number of statements that can appear in the body of an <tt>if</tt> statement, 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.

As an aside, if you need to check the parity (evenness or oddness) of numbers often, you might wrap this code in a function:

For any value of <tt>x</tt>, <tt>print_parity</tt> displays an appropriate message. When you call it, you can provide any integer expression as an argument.

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 of the number of <tt>elif</tt> statements but only a single (and optional) <tt>else</tt> statement is allowed and it must be the last branch in the statement:

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

The outer conditional contains two branches. The first branch contains a simple output statement. The second branch contains another <tt>if</tt> statement, which has two branches of its own. Those two branches are both output 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 the conditionals, so we can use the <tt>and</tt> operator:

These kinds of conditions are common, so Python provides an alternative syntax that is similar to mathematical notation:

This condition is semantically the same as the compound boolean expression and the nested conditional.

The <tt>return</tt> statement
The <tt>return</tt> statement allows you to terminate the execution of a function before you reach the end. One reason to use it is if you detect an error condition:

The function <tt>print_square_root</tt> has a parameter named <tt>x</tt>. The first thing it does is check whether <tt>x</tt> is less than or equal to 0, in which case it displays an error message and then uses <tt>return</tt> to exit the function. The flow of execution immediately returns to the caller, and the remaining lines of the function are not executed.

Keyboard input
In :ref:`input` we were introduced to Python's built-in functions that get input from the keyboard: <tt>raw_input</tt> and <tt>input</tt>. Now let's look at these again in greater depth.

When either of these functions are called, the program stops and waits for the user to type something. When the user presses Return or the Enter key, the program resumes and <tt>raw_input</tt> returns what the user typed as a <tt>string</tt>:

Before calling <tt>raw_input</tt>, it is a good idea to print a message telling the user what to input. This message is called a prompt. We can supply a prompt as an argument to <tt>raw_input</tt>:

Notice that the prompt is a string, so it must be enclosed in quotation marks.

If we expect the response to be an integer, we can use the <tt>input</tt> function which evaluates the response as a Python expression:

If the user types a string of digits, it is converted to an integer and assigned to <tt>speed</tt>. Unfortunately, if the user types characters that do not make up a valid Python expression, the program crashes:

In the last example, if the user had made the response a valid Python expression by putting quotes around it, it would not have given an error:

To avoid this kind of error, it is a good idea to use <tt>raw_input</tt> to get a string and then use conversion commands to convert it to other types.

Type conversion
Each Python type comes with a built-in command that attempts to convert values of another type into that type. The <tt>int(ARGUMENT)</tt> command, for example, takes any value and converts it to an integer, if possible, or complains otherwise:

<tt>int</tt> can also convert floating-point values to integers, but remember that it truncates the fractional part:

The <tt>float(ARGUMENT)</tt> command converts integers and strings to floating-point numbers:

It may seem odd that Python distinguishes the integer value <tt>1</tt> from the floating-point value <tt>1.0</tt>. They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

The <tt>str(ARGUMENT)</tt> command converts any argument given to it to type <tt>string</tt>:

<tt>str(ARGUMENT)</tt> will work with any value and convert it into a string. As mentioned earlier, <tt>True</tt> is boolean value; <tt>true</tt> is not.

For boolean values, the situation is especially interesting:

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

GASP
GASP (G raphics A PI for S tudents of P ython) will enable us to write programs involving graphics. Before you can use GASP, it needs to be installed on your machine. If you are running Ubuntu GNU/Linux, see :ref:`installing-gasp` in Appendix A_. Current instructions for installing GASP on other platforms can be found at [http://dev.laptop.org/pub/gasp/downloads. http://dev.laptop.org/pub/gasp/downloads.]

After installing gasp, try the following python script:

The second to the last command pauses and waits until a key is pressed. Without it, the screen would flash by so quickly you wouldn't see it.

Running this script, you should see a graphics window that looks like this:

We will be using gasp from here on to illustrate (pun intended) computer programming concepts and to add to our fun while learning. You can find out more about the GASP module by reading Appendix B_.

Exercises
<dl> <dt>#. Try to evaluate the following numerical expressions in your head, then use</dt> <dd> the Python interpreter to check your results: <ol> <li><tt>&gt;&gt;&gt; 5 % 2</tt></li> <li><tt>&gt;&gt;&gt; 9 % 5</tt></li> <li><tt>&gt;&gt;&gt; 15 % 12</tt></li> <li><tt>&gt;&gt;&gt; 12 % 15</tt></li> <li><tt>&gt;&gt;&gt; 6 % 6</tt></li> <li><tt>&gt;&gt;&gt; 0 % 7</tt></li> <li><tt>&gt;&gt;&gt; 7 % 0</tt></li></ol> What happened with the last example? Why? If you were able to correctly anticipate the computer's response in all but the last one, it is time to move on. If not, take time now to make up examples of your own. Explore the modulus operator until you are confident you understand how it works. </dd> <dt>#.</dt> <dd> Wrap this code in a function called <tt>compare(x, y)</tt>. Call <tt>compare</tt> three times: one each where the first argument is less than, greater than, and equal to the second argument. </dd> <dt>#. To better understand boolean expressions, it is helpful to construct truth</dt> <dd> tables. Two boolean expressions are logically equivalent if and only if they have the same truth table. The following Python script prints out the truth table for the any boolean expression in two variables: p and q:

You will learn how this script works in later chapters. For now, you will use it to learn about boolean expressions. Copy this program to a file named <tt>p_and_q.py</tt>, then run it from the command line and give it: <tt>p or q</tt>, when prompted for a boolean expression. You should get the following output: p     q      p or q "===================== True True True True False True False True True False False False" Now that we see how it works, let's wrap it in a function to make it easier to use:

We can import it into a Python shell and call <tt>truth_table</tt> with a string containing our boolean expression in p and q as an argument:

Use the <tt>truth_table</tt> functions with the following boolean expressions, recording the truth table produced each time: <ol> <li>not(p or q)</li> <li>p and q</li> <li>not(p and q)</li> <li>not(p) or not(q)</li> <li>not(p) and not(q)</li></ol> Which of these are logically equivalent? </dd></dl>


 * 1) . Enter the following expressions into the Python shell:

Analyze these results. What observations can you make about values of different types and logical operators? Can you write these observations in the form of simple rules about <tt>and</tt> and <tt>or</tt> expressions? <dl> <dt>#.</dt> <dd> Wrap this code in a function called <tt>dispatch(choice)</tt>. Then define <tt>function_a</tt>, <tt>function_b</tt>, and <tt>function_c</tt> so that they print out a message saying they were called. For example:

Put the four functions ( <tt>dispatch</tt>, <tt>function_a</tt>, <tt>function_b</tt>, and <tt>function_c</tt> into a script named <tt>ch04e05.py</tt>. At the bottom of this script add a call to <tt>dispatch('b')</tt>. Your output should be: function_b was called...  Finally, modify the script so that user can enter 'a', 'b', or 'c'. Test it by importing your script into the Python shell. </dd> <dt>#. Write a function named <tt>is_divisible_by_3</tt> that takes a single integer as</dt> <dd> an argument and prints &quot;This number is divisible by three.&quot; if the argument is evenly divisible by 3 and &quot;This number is not divisible by three.&quot; otherwise.  Now write a similar function named <tt>is_divisible_by_5</tt>. </dd> <dt>#. Generalize the functions you wrote in the previous exercise into a function</dt> <dd> named <tt>is_divisible_by_n(x, n)</tt> that takes two integer arguments and prints out whether the first is divisible by the second. Save this in a file named <tt>ch04e07.py</tt>. Import it into a shell and try it out. A sample session might look like this: </dd></dl>

<ol> <li> What will be the output of the following?

Explain what happened and why it happened.</li> <li> The following gasp script, in a file named <tt>house.py</tt>, draws a simple house on a gasp canvas:

Run this script and confirm that you get a window that looks like this: <ol> <li>Wrap the house code in a function named <tt>draw_house</tt>.</li> <li>Run the script now. Do you see a house? Why not?</li> <li>Add a call to <tt>draw_house</tt> at the botton of the script so that the house returns to the screen.</li> <li>Parameterize the function with x and y parameters -- the header should then become <tt>def draw_house(x, y):</tt>, so that you can pass in the location of the house on the canvas.</li></ol>

<dl> <dt>#. Use <tt>draw_house</tt> to place five houses on the canvas in different</dt> <dd> locations. </dd></dl> </li> <li> Exploration: Read over Appendix B_ and write a script named <tt>houses.py</tt> that produces the following when run: hint: You will need to use a <tt>Polygon</tt> for the roof instead of two <tt>Line</tt>s to get <tt>filled=True</tt> to work with it. </li></ol>