4.1. The modulus operator¶

The modulus operator works on integers (and integer expressions) and yieldsthe remainder when the first operand is divided by the second. In Python, themodulus operator is a percent sign (%). The syntax is the same as for otheroperators:


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

You are watching: What is the result of the following boolean expression, if x equals 5, y equals 3, and z equals 8?

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

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


4.2. Boolean values and expressions¶

The Python type for storing true and false values is called bool, namedafter the British mathematician, George Boole. George Boole created Booleanalgebra, which is the basis of all modern computer arithmetic.

There are only two boolean values: True and False. Capitalizationis important, since true and false are not boolean values.


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


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

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


x != y # x is not equal to yx > y # x is greater than yx y # x is less than yx >= y # x is greater than or equal to yx y # x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols aredifferent from the mathematical symbols. A common error is to use a singleequal sign (=) instead of a double equal sign (==). Remember that =is an assignment operator and == is a comparison operator. Also, there isno such thing as = or =>.


4.3. Logical operators¶

There are three logical operators: and, or, and not. Thesemantics (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 andless 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 toy.


4.4. Conditional execution¶

In order to write useful programs, we almost always need the ability to checkconditions and change the behavior of the program accordingly. Conditionalstatements give us this ability. The simplest form is the ** ifstatement**:


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

The syntax for an if statement looks like this:


As with the function definition from last chapter and other compoundstatements, the if statement consists of a header and a body. The headerbegins with the keyword if followed by a boolean expression and ends witha colon (:).

The indented statements that follow are called a block. The firstunindented statement marks the end of the block. A statement blockinside a compound statement is called the body of the statement.

Each of the statements inside the body are executed in order if the booleanexpression evaluates to True. The entire block is skipped if the booleanexpression evaluates to False.

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


4.5. Alternative execution¶

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


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

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


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


4.6. Chained conditionals¶

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


if x y: print x, "is less than", yelif x > y: print x, "is greater than", yelse: print x, "and", y, "are equal"
elif is an abbreviation of else if . Again, exactly one branch will beexecuted. There is no limit of the number of elif statements but only asingle (and optional) else statement is allowed and it must be the lastbranch in the statement:


if choice == 'a': function_a()elif choice == 'b': function_b()elif choice == 'c': function_c()else: print "Invalid choice."
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 thestatement ends. Even if more than one condition is true, only the first truebranch executes.


4.7. Nested conditionals¶

One conditional can also be nested within another. We could have writtenthe trichotomy example as follows:


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 simpleoutput statement. The second branch contains another if statement, whichhas 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, nestedconditionals become difficult to read very quickly. In general, it is a goodidea to avoid them when you can.

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


The print statement is executed only if we make it past both theconditionals, so we can use the and operator:


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


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


4.8. The return statement¶

The return statement allows you to terminate the execution of a functionbefore you reach the end. One reason to use it is if you detect an errorcondition:


def print_square_root(x): if x 0: print "Positive numbers only, please." return result = x**0.5 print "The square root of", x, "is", result
The function print_square_root has a parameter named x. The first thingit does is check whether x is less than or equal to 0, in which case itdisplays an error message and then uses return to exit the function. Theflow of execution immediately returns to the caller, and the remaining lines ofthe function are not executed.


4.9. Keyboard input¶

In Input we were introduced to Python’s built-in functions that getinput from the keyboard: raw_input and input. Now let’s look at theseagain in greater depth.

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


Before calling raw_input, it is a good idea to print a message telling theuser what to input. This message is called a prompt. We can supply aprompt as an argument to raw_input:


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 input functionwhich evaluates the response as a Python expression:


If the user types a string of digits, it is converted to an integer andassigned to speed. Unfortunately, if the user types characters that do notmake up a valid Python expression, the program crashes:


In the last example, if the user had made the response a valid Pythonexpression 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 raw_input to get astring and then use conversion commands to convert it to other types.


4.10. Type conversion¶

Each Python type comes with a built-in command that attempts to convert valuesof another type into that type. The int(ARGUMENT) command, for example,takes any value and converts it to an integer, if possible, or complainsotherwise:


int can also convert floating-point values to integers, but rememberthat it truncates the fractional part:


The float(ARGUMENT) command converts integers and strings to floating-pointnumbers:


It may seem odd that Python distinguishes the integer value 1 from thefloating-point value 1.0. They may represent the same number, but theybelong to different types. The reason is that they are represented differentlyinside the computer.

The str(ARGUMENT) command converts any argument given to it to typestring:


str(ARGUMENT) will work with any value and convert it into a string. Asmentioned earlier, True is boolean value; true is not.

For boolean values, the situation is especially interesting:


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


4.11. GASP¶

GASP (Graphics API for Students of Python) will enableus to write programs involving graphics. Before you can use GASP, it needsto be installed on your machine. If you are running Ubuntu GNU/Linux, seeGASP in Appendix A. Current instructionsfor installing GASP on other platforms can be found athttp://dev.laptop.org/pub/gasp/downloads.

After installing gasp, try the following python script:


from gasp import *begin_graphics()Circle((200, 200), 60)Line((100, 400), (580, 200))Box((400, 350), 120, 100)update_when('key_pressed')end_graphics()
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) computerprogramming concepts and to add to our fun while learning. You can find outmore about the GASP module by reading Appendix B.


4.12. Glossary¶

blockA group of consecutive statements with the same indentation.bodyThe block of statements in a compound statement that follows theheader.boolean expressionAn expression that is either true or false.boolean valueThere are exactly two boolean values: True and False. Booleanvalues result when a boolean expression is evaluated by the Pythoninterepreter. They have type bool.branchOne of the possible paths of the flow of execution determined byconditional execution.chained conditionalA conditional branch with more than two possible flows of execution. InPython chained conditionals are written with if ... elif ... elsestatements.comparison operatorOne of the operators that compares two values: ==, !=, >,, >=, and .conditionThe boolean expression in a conditional statement that determines whichbranch is executed.conditional statementA statement that controls the flow of execution depending on somecondition. In Python the keywords if, elif, and else areused for conditional statements.logical operatorOne of the operators that combines boolean expressions: and,or, and not.modulus operatorAn operator, denoted with a percent sign ( %), that works onintegers and yields the remainder when one number is divided byanother.nestingOne program structure within another, such as a conditional statementinside a branch of another conditional statement.promptA visual cue that tells the user to input data.type conversionAn explicit statement that takes a value of one type and computes acorresponding value of another type.wrapping code in a functionThe process of adding a function header and parameters to a sequenceof program statements is often refered to as “wrapping the code ina function”. This process is very useful whenever the programstatements in question are going to be used multiple times.

4.13. Exercises¶

Try to evaluate the following numerical expressions in your head, then usethe Python interpreter to check your results:


What happened with the last example? Why? If you were able to correctlyanticipate the computer’s response in all but the last one, it is time tomove on. If not, take time now to make up examples of your own. Explore themodulus operator until you are confident you understand how it works.


if x y: print x, "is less than", yelif x > y: print x, "is greater than", yelse: print x, "and", y, "are equal"
Wrap this code in a function called compare(x, y). Call comparethree times: one each where the first argument is less than, greaterthan, and equal to the second argument.

To better understand boolean expressions, it is helpful to construct truthtables. Two boolean expressions are logically equivalent if and only ifthey have the same truth table.

The following Python script prints out the truth table for any booleanexpression in two variables: p and q:


expression = raw_input("Enter a boolean expression in two variables, p and q: ")print " p q %s" % expressionlength = len( " p q %s" % expression)print length*"="for p in True, False: for q in True, False: print "%-7s %-7s %-7s" % (p, q, eval(expression))
You will learn how this script works in later chapters. For now, youwill use it to learn about boolean expressions. Copy this program to afile named p_and_q.py, then run it from the command line and giveit: p or q, when prompted for a boolean expression. You should getthe following output:


def truth_table(expression): print " p q %s" % expression length = len( " p q %s" % expression) print length*"=" for p in True, False: for q in True, False: print "%-7s %-7s %-7s" % (p, q, eval(expression))
We can import it into a Python shell and call truth_table with a stringcontaining our boolean expression in p and q as an argument:


Use the truth_table functions with the following boolean expressions,recording the truth table produced each time:


True or FalseTrue and Falsenot(False) and TrueTrue or 7False or 7True and 0False or 8"happy" and "sad""happy" or "sad""" and "sad""happy" and ""
Analyze these results. What observations can you make about values ofdifferent types and logical operators? Can you write these observations inthe form of simple rules about and and or expressions?


if choice == 'a': function_a()elif choice == 'b': function_b()elif choice == 'c': function_c()else: print "Invalid choice."
Wrap this code in a function called dispatch(choice). Then definefunction_a, function_b, and function_c so that they print out amessage saying they were called. For example:


Put the four functions ( dispatch, function_a, function_b, andfunction_c into a script named ch04e05.py. At the bottom of thisscript add a call to dispatch("b"). Your output should be:


Finally, modify the script so that user can enter ‘a’, ‘b’, or ‘c’. Test itby importing your script into the Python shell.

Write a function named is_divisible_by_3 that takes a single integer asan argument and prints “This number is divisible by three.” if the argumentis evenly divisible by 3 and “This number is not divisible by three.”otherwise.

Now write a similar function named is_divisible_by_5.

Generalize the functions you wrote in the previous exercise into a functionnamed is_divisible_by_n(x, n) that takes two integer arguments andprints out whether the first is divisible by the second. Save this in afile named ch04e07.py. Import it into a shell and try it out. A samplesession might look like this:


if "Ni!": print 'We are the Knights who say, "Ni!"'else: print "Stop it! No more of this!"if 0: print "And now for something completely different..."else: print "What's all this, then?"
Explain what happened and why it happened.

The following gasp script, in a file named house.py, draws a simplehouse on a gasp canvas:


from gasp import * # import everything from the gasp librarybegin_graphics() # open the graphics canvasBox((20, 20), 100, 100) # the houseBox((55, 20), 30, 50) # the doorBox((40, 80), 20, 20) # the left windowBox((80, 80), 20, 20) # the right windowLine((20, 120), (70, 160)) # the left roofLine((70, 160), (120, 120)) # the right roofupdate_when('key_pressed') # keep the canvas open until a key is pressedend_graphics() # close the canvas (which would happen # anyway, since the script ends here, but it # is better to be explicit).
Run this script and confirm that you get a window that looks likethis:

*
Wrap the house code in a function named draw_house().Run the script now. Do you see a house? Why not?Add a call to draw_house() at the botton of the script so that thehouse returns to the screen.

See more: You Are Not Alone Micheal Jackson Lyrics, Michael Jackson

Parameterize the function with x and y parameters – the headershould then become def draw_house(x, y):, so that you can pass inthe location of the house on the canvas.Use draw_house to place five houses on the canvas in differentlocations.