3.1. If Statements¶
3.1.1. Simple Conditions¶
The statements introduced in this chapter will involve tests or conditions. More syntax for conditions will be introduced later, but for now consider simple arithmetic comparisons that directly translate from math into Python. Try each line separately in the Shell
You see that conditions are either or (with no quotes!). These are the only possible Boolean values (named after 19th century mathematician George Boole). In Python the name Boolean is shortened to the type . It is the type of the results of true-false conditions or tests.
3.1.2. Simple Statements¶
Run this example program, suitcase.py. Try it at least twice, with inputs: 30 and then 55. As you an see, you get an extra result, depending on the input. The main code is:
The middle two line are an statement. It reads pretty much like English. If it is true that the weight is greater than 50, then print the statement about an extra charge. If it is not true that the weight is greater than 50, then don’t do the indented part: skip printing the extra luggage charge. In any event, when you have finished with the statement (whether it actually does anything or not), go on to the next statement that is not indented under the . In this case that is the statement printing “Thank you”.
The general Python syntax for a simple statement is
If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements.
Another fragment as an example:
As with other kinds of statements with a heading and an indented block, the block can have more than one statement. The assumption in the example above is that if an account goes negative, it is brought back to 0 by transferring money from a backup account in several steps.
In the examples above the choice is between doing something (if the condition is ) or nothing (if the condition is ). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition.
3.1.3. - Statements¶
Run the example program, . Try it at least twice, with inputs 50 and then 80. As you can see, you get different results, depending on the input. The main code of is:
The middle four lines are an if-else statement. Again it is close to English, though you might say “otherwise” instead of “else” (but else is shorter!). There are two indented blocks: One, like in the simple statement, comes right after the heading and is executed when the condition in the heading is true. In the - form this is followed by an line, followed by another indented block that is only executed when the original condition is false. In an - statement exactly one of two possible indented blocks is executed.
A line is also shown outdented next, about getting exercise. Since it is outdented, it is not a part of the if-else statement: It is always executed in the normal forward flow of statements, after the - statement (whichever block is selected).
The general Python - syntax is
These statement blocks can have any number of statements, and can include about any kind of statement.
See Graduate Exercise
3.1.4. More Conditional Expressions¶
All the usual arithmetic comparisons may be made, but many do not use standard mathematical symbolism, mostly for lack of proper keys on a standard keyboard.
|Meaning||Math Symbol||Python Symbols|
|Less than or equal||≤|
|Greater than or equal||≥|
There should not be space between the two-symbol Python substitutes.
Notice that the obvious choice for equals, a single equal sign, is not used to check for equality. An annoying second equal sign is required. This is because the single equal sign is already used for assignment in Python, so it is not available for tests.
It is a common error to use only one equal sign when you mean to test for equality, and not make an assignment!
Tests for equality do not make an assignment, and they do not require a variable on the left. Any expressions can be tested for equality or inequality (!=). They do not need to be numbers! Predict the results and try each line in the Shell:
An equality check does not make an assignment. Strings are case sensitive. Order matters in a list.
Try in the Shell:
When the comparison does not make sense, an Exception is caused. 
Following up on the discussion of the inexactness of float arithmetic in String Formats for Float Precision, confirm that Python does not consider .1 + .2 to be equal to .3: Write a simple condition into the Shell to test.
Here is another example: Pay with Overtime. Given a person’s work hours for the week and regular hourly wage, calculate the total pay for the week, taking into account overtime. Hours worked over 40 are overtime, paid at 1.5 times the normal rate. This is a natural place for a function enclosing the calculation.
Read the setup for the function:
The problem clearly indicates two cases: when no more than 40 hours are worked or when more than 40 hours are worked. In case more than 40 hours are worked, it is convenient to introduce a variable overtimeHours. You are encouraged to think about a solution before going on and examining mine.
You can try running my complete example program, wages.py, also shown below. The format operation at the end of the main function uses the floating point format (String Formats for Float Precision) to show two decimal places for the cents in the answer:
Here the input was intended to be numeric, but it could be decimal so the conversion from string was via , not .
Below is an equivalent alternative version of the body of , used in . It uses just one general calculation formula and sets the parameters for the formula in the statement. There are generally a number of ways you might solve the same problem!
126.96.36.199. Graduate Exercise¶
Write a program, , that prompts students for how many credits they have. Print whether of not they have enough credits for graduation. (At Loyola University Chicago 120 credits are needed for graduation.)
188.8.131.52. Head or Tails Exercise¶
Write a program . It should include a function , that simulates a single flip of a coin: It randomly prints either or . Accomplish this by choosing 0 or 1 arbitrarily with , and use an - statement to print when the result is 0, and otherwise.
In your main program have a simple repeat loop that calls 10 times to test it, so you generate a random sequence of 10 and .
184.108.40.206. Strange Function Exercise¶
Save the example program as , and complete the definitions of functions and as described in the function documentation strings in the program. In the function definition use an - statement (hint ). In the function definition use a -each loop, the range function, and the jump function.
The function is introduced for use in Strange Sequence Exercise, and others after that.
3.1.5. Multiple Tests and - Statements¶
Often you want to distinguish between more than two distinct cases, but conditions only have two possible results, or , so the only direct choice is between two options. As anyone who has played “20 Questions” knows, you can distinguish more cases by further questions. If there are more than two choices, a single test may only reduce the possibilities, but further tests can reduce the possibilities further and further. Since most any kind of statement can be placed in an indented statement block, one choice is a further statement. For instance consider a function to convert a numerical grade to a letter grade, ‘A’, ‘B’, ‘C’, ‘D’ or ‘F’, where the cutoffs for ‘A’, ‘B’, ‘C’, and ‘D’ are 90, 80, 70, and 60 respectively. One way to write the function would be test for one grade at a time, and resolve all the remaining possibilities inside the next clause:
This repeatedly increasing indentation with an statement as the block can be annoying and distracting. A preferred alternative in this situation, that avoids all this indentation, is to combine each and block into an block:
The most elaborate syntax for an -- statement is indicated in general below:
The , each , and the final line are all aligned. There can be any number of lines, each followed by an indented block. (Three happen to be illustrated above.) With this construction exactlyone of the indented blocks is executed. It is the one corresponding to the first condition, or, if all conditions are , it is the block after the final line.
Be careful of the strange Python contraction. It is , not . A program testing the letterGrade function is in example program .
See Grade Exercise.
A final alternative for statements: --.... with no. This would mean changing the syntax for -- above so the final and the block after it would be omitted. It is similar to the basic statement without an , in that it is possible for no indented block to be executed. This happens if none of the conditions in the tests are true.
With an included, exactly one of the indented blocks is executed. Without an , at most one of the indented blocks is executed.
This - statement only prints a line if there is a problem with the weight of the suitcase.
220.127.116.11. Sign Exercise¶
Write a program to ask the user for a number. Print out which category the number is in: , , or .
18.104.22.168. Grade Exercise¶
In Idle, load and save it as Modify so it has an equivalent version of the letterGrade function that tests in the opposite order, first for F, then D, C, .... Hint: How many tests do you need to do? 
Be sure to run your new version and test with different inputs that test all the different paths through the program.
22.214.171.124. Wages Exercise¶
* Modify the or the example to create a program that assumes people are paid double time for hours over 60. Hence they get paid for at most 20 hours overtime at 1.5 times the normal rate. For example, a person working 65 hours with a regular wage of $10 per hour would work at $10 per hour for 40 hours, at 1.5 * $10 for 20 hours of overtime, and 2 * $10 for 5 hours of double time, for a total of
10*40 + 1.5*10*20 + 2*10*5 = $800.
You may find easier to adapt than .
3.1.6. Nesting Control-Flow Statements¶
The power of a language like Python comes largely from the variety of ways basic statements can be combined. In particular, and statements can be nested inside each other’s indented blocks. For example, suppose you want to print only the positive
numbers from an arbitrary list of numbers in a function with the following heading. Read the pieces for now.
For example, suppose is . You want to process a list, so that suggests a -each loop,
but a -each loop runs the same code body for each element of the list, and we only want
for some of them. That seems like a major obstacle, but think closer at what needs to happen concretely. As a human, who has eyes of amazing capacity, you are drawn immediately to the actual correct numbers, 3, 2, and 7, but clearly a computer doing this systematically will have to check every number. In fact, there is a consistent action required: Every number must be tested to see if it should be printed. This suggests an statement, with the condition . Try loading into Idle and running the example program , whose code is shown below. It ends with a line testing the function:
This idea of nesting statements enormously expands the possibilities with loops. Now different things can be done at different times in loops, as long as there is a consistent test to allow a choice between the alternatives. Shortly, loops will also be introduced, and you will see statements nested inside of them, too.
The rest of this section deals with graphical examples.
Run example program . It has a red ball moving and bouncing obliquely off the edges. If you watch several times, you should see that it starts from random locations. Also you can repeat the program from the Shell prompt after you have run the script. For instance, right after running the program, try in the Shell
The parameters give the amount the shape moves in each animation step. You can try other values in the Shell, preferably with magnitudes less than 10.
For the remainder of the description of this example, read the extracted text pieces.
The animations before this were totally scripted, saying exactly how many moves in which direction, but in this case the direction of motion changes with every bounce. The program has a graphic object and the central animation step is
but in this case, dx and dy have to change when the ball gets to a boundary. For instance, imagine the ball getting to the left side as it is moving to the left and up. The bounce obviously alters the horizontal part of the motion, in fact reversing it, but the ball would still continue up. The reversal of the horizontal part of the motion means that the horizontal shift changes direction and therefore its sign:
but does not need to change. This switch does not happen at each animation step, but only when the ball reaches the edge of the window. It happens only some of the time - suggesting an statement. Still the condition must be determined. Suppose the center of the ball has coordinates (x, y). When x reaches some particular x coordinate, call it xLow, the ball should bounce.
The edge of the window is at coordinate 0, but should not be 0, or the ball would be half way off the screen before bouncing! For the edge of the ball to hit the edge of the screen, the x coordinate of the center must be the length of the radius away, so actually is the radius of the ball.
Animation goes quickly in small steps, so I cheat. I allow the ball to take one (small, quick) step past where it really should go (), and then we reverse it so it comes back to where it belongs. In particular
There are similar bounding variables , and , all the radius away from the actual edge coordinates, and similar conditions to test for a bounce off each possible edge. Note that whichever edge is hit, one coordinate, either dx or dy, reverses. One way the collection of tests could be written is
This approach would cause there to be some extra testing: If it is true that , then it is impossible for it to be true that , so we do not need both tests together. We avoid unnecessary tests with an elif clause (for both x and y):
Note that the middle is not changed to an , because it is possible for the ball to reach a corner, and need both and reversed.
The program also uses several accessor methods for graphics objects that we have not used in examples yet. Various graphics objects, like the circle we are using as the shape, know their center point, and it can be accessed with the method. (Actually a clone of the point is returned.) Also each coordinate of a can be accessed with the and methods.
This explains the new features in the central function defined for bouncing around in a box, . The animation arbitrarily goes on in a simple repeat loop for 600 steps. (A later example will improve this behavior.)
The program starts the ball from an arbitrary point inside the allowable rectangular bounds. This is encapsulated in a utility function included in the program, . The getRandomPoint function uses the function from the module . Note that in parameters for both the functions and , the end stated is past the last value actually desired:
The full program is listed below, repeating and for completeness. Several parts that may be useful later, or are easiest to follow as a unit, are separated out as functions. Make sure you see how it all hangs together or ask questions!
126.96.36.199. Short String Exercise¶
Write a program with a function with heading:
In your main program, test the function, calling it several times with different lists of strings. Hint: Find the length of each string with the function.
The function documentation here models a common approach: illustrating the behavior of the function with a Python Shell interaction. This begins with a line starting with . Other exercises and examples will also document behavior in the Shell.
188.8.131.52. Even Print Exercise¶
Write a program with a function with heading:
In your main program, test the function, calling it several times with different lists of integers. Hint: A number is even if its remainder, when dividing by 2, is 0.
184.108.40.206. Even List Exercise¶
Write a program with a function with heading:
In your main program, test the function, calling it several times with different lists of integers and printing the results. Hint: Create a new list, and append the appropriate numbers to it.
220.127.116.11. Unique List Exercise¶
* The program has its function, which first generates a list of each occurrence of a cue in the story format. This gives the cues in order, but likely includes repetitions. The original version of uses a quick method to remove duplicates, forming a set from the list. There is a disadvantage in the conversion, though: Sets are not ordered, so when you iterate through the resulting set, the order of the cues will likely bear no resemblance to the order they first appeared in the list. That issue motivates this problem:
Copy to , and add a function with this heading:
A useful Boolean operator is , checking membership in a sequence:
It can also be used with , as , to mean the opposite:
In general the two versions are:
Hint: Process in order. Use the new syntax to only append elements to a new list that are not already in the new list.
After perfecting the function, replace the last line of , so it uses to remove duplicates in .
Check that your prompts you for cue values in the order that the cues first appear in the madlib format string.
3.1.7. Compound Boolean Expressions¶
To be eligible to graduate from Loyola University Chicago, you must have 120 credits and a GPA of at least 2.0. This translates directly into Python as a compound condition:
This is true if both is true and is true. A short example program using this would be:
The new Python syntax is for the operator :
The compound condition is true if both of the component conditions are true. It is false if at least one of the conditions is false.
See Congress Exercise.
In the last example in the previous section, there was an - statement where both tests had the same block to be done if the condition was true:
There is a simpler way to state this in a sentence: If x < xLow or x > xHigh, switch the sign of dx. That translates directly into Python:
The word makes another compound condition:
is true if at least one of the conditions is true. It is false if both conditions are false. This corresponds to one way the word “or” is used in English. Other times in English “or” is used to mean exactly one alternative is true.
When translating a problem stated in English using “or”, be careful to determine whether the meaning matches Python’s .
It is often convenient to encapsulate complicated tests inside a function. Think how to complete the function starting:
Recall that a is specified in its constructor by two diagonally oppose s. This example gives the first use in the tutorials of the methods that recover those two corner points, and . The program calls the points obtained this way and . The x and y coordinates of , , and can be recovered with the methods of the type, and .
Suppose that I introduce variables for the x coordinates of , , and , calling these x-coordinates , , and , respectively. On first try you might decide that the needed mathematical relationship to test is
Unfortunately, this is not enough: The only requirement for the two corner points is that they be diagonally opposite, not that the coordinates of the second point are higher than the corresponding coordinates of the first point. It could be that is 200; is 100, and is 120. In this latter case is between and , but substituting into the expression above
is False. The 100 and 200 need to be reversed in this case. This makes a complicated situation. Also this is an issue which must be revisited for both the x and y coordinates. I introduce an auxiliary function to deal with one coordinate at a time. It starts:
Clearly this is true if the original expression, , is true. You must also consider the possible case when the order of the ends is reversed: . How do we combine these two possibilities? The Boolean connectives to consider are and . Which applies? You only need one to be true, so is the proper connective:
A correct but redundant function body would be:
Check the meaning: if the compound expression is , return . If the condition is , return - in either case return the same value as the test condition. See that a much simpler and neater version is to just return the value of the condition itself!
In general you should not need an - statement to choose between true and false values! Operate directly on the boolean expression.
A side comment on expressions like
Other than the two-character operators, this is like standard math syntax, chaining comparisons. In Python any number of comparisons can be chained in this way, closely approximating mathematical notation. Though this is good Python, be aware that if you try other high-level languages like Java and C++, such an expression is gibberish. Another way the expression can be expressed (and which translates directly to other languages) is:
So much for the auxiliary function . Back to the function. You can use the function to check the x coordinates,
and to check the y coordinates,
Again the question arises: how do you combine the two tests?
In this case we need the point to be both between the sides and between the top and bottom, so the proper connector is and.
Think how to finish the method. Hint: 
Sometimes you want to test the opposite of a condition. As in English you can use the word . For instance, to test if a Point was not inside Rectangle Rect, you could use the condition
is when condition is , and when condition is .
The example program , shown below, is a complete program using the function in a simple application, choosing colors. Pardon the length. Do check it out. It will be the starting point for a number of improvements that shorten it and make it more powerful in the next section. First a brief overview:
The program includes the functions and that have already been discussed. The program creates a number of colored rectangles to use as buttons and also as picture components. Aside from specific data values, the code to create each rectangle is the same, so the action is encapsulated in a function, . All of this is fine, and will be preserved in later versions.
The present main function is long, though. It has the usual graphics starting code, draws buttons and picture elements, and then has a number of code sections prompting the user to choose a color for a picture element. Each code section has a long -- test to see which button was clicked, and sets the color of the picture element appropriately.
6. Ternary Operators¶
Ternary operators are more commonly known as conditional expressions in Python. These operators evaluate something based on a condition being true or not. They became a part of Python in version 2.4
Here is a blueprint and an example of using these conditional expressions.
It allows to quickly test a condition instead of a multiline if statement. Often times it can be immensely helpful and can make your code compact but still maintainable.
Another more obscure and not widely used example involves tuples. Here is some sample code:
This works simply because True == 1 and False == 0, and so can be done with lists in addition to tuples.
The above example is not widely used and is generally disliked by Pythonistas for not being Pythonic. It is also easy to confuse where to put the true value and where to put the false value in the tuple.
Another reason to avoid using a tupled ternery is that it results in both elements of the tuple being evaluated, whereas the if-else ternary operator does not.
This happens because with the tupled ternary technique, the tuple is first built, then an index is found. For the if-else ternary operator, it follows the normal if-else logic tree. Thus, if one case could raise an exception based on the condition, or if either case is a computation-heavy method, using tuples is best avoided.