Conditionals & Logic “Finger Exercises”
if
Statement
We'll introduce the syntax of an if
statement by a series
of examples.
To choose the larger of two values, we can define the following function.
-
def max2(x,y): if x > y: return x else: return y
Similarly, to choose the largest of three values, we can define the following.
-
def max3(x,y,z): if x > y and x > z: return x elif y > x and y > z: return y else: return z
Try these two functions on some sample inputs.
We could continue defining max
functions in a similar vein,
but Python gives us an easier option,
a built-in function max
which allows any number of
arguments.
When doing some operations, it is useful to first check for a possible error condition. For example,
-
# Define a couple sample values: x=4 y=8 # Print the result of dividing: if y==0: print "Cannot divide ", x, " by zero." else: print x/y
Change y
to zero and run this again.
In the above example, note that we compare equality with
==
(double equals), not =
(single equals).
We've already been using the single equals sign in the course, as its
purpose is to assign a value to a variable.
Do not confuse these two.
Alternately, if we don't want an error message:
-
# Define a couple sample values: x=4 y=8 # Print the result of dividing: if y!=0: print x/y
Comparison Operators
The previous examples illustrate several ways of comparing two values.
These return one of two possible truth values,
True
and False
, also known as
Boolean values.
For example, the following illustrate the most common comparisons. For each one, guess what the result is, then type it in to see if you were right.
-
3 == 3
-
3 == 4
Once again, we compare equality with two equals signs (==
), not
one (=
).
-
"abc" == "abc"
-
"xyzzy" == "Hi"
-
3 != 3
-
3 != 4
-
"abc" != "abc"
-
"xyzzy" != "Hi"
-
3 > 2
-
3 > 4
-
"a" > "b"
-
"b" > "a"
-
"abc" > "abb"
-
3 < 2
-
3 < 4
-
"a" < "b"
-
"b" < "a"
-
"abc" < "abb"
-
"xy" < "abc"
There are also >=
(greater than or equal) and
<=
(less than or equal) which work as expected.
Booleans are just another kind of value that you can assign to variables and pass to functions, as in the following.
-
def silly(b): if b: print "Yes, siree!" else: print "No way!" x = (3>2) print x silly(x)
Logic
You can combine comparisons with the operators and
,
or
, and not
, as in the following examples:
-
(3>2) and (8<10)
-
(3>2) and (8>10)
-
not (8>10)
-
(2<3) or (8>10)
-
not ((2<3) or (8>10))
Most of the above parentheses are not necessary, but we recommend including them, rather than depending on operator precedence. Try typing the examples in fewer parentheses to see which expressions still have the same results.
Additional optional readings about Python conditionals
- Wikibooks: Python Programming Conditionals
Combining conditionals with loops
Conditionals are often used within loops. We saw one example in the
modified predator-prey code. Often, conditionals are used to check
if the loop should stop early. Here are two similar functions for
searching a list for a specific item. One merely prints the results,
while the other returns True
or False
,
indicating whether the item was found.
-
def searchList1(aValue, aList): for x in aList: if x == aValue: return aValue, " is in the list ", aList return aValue, " is not in the list ", aList searchList1(3,[1,8,2,6]) searchList1(3,[1,8,3,2,6])
-
def searchList2(aValue, aList): for x in aList: if x == aValue: return True return False searchList2(3,[1,8,2,6]) searchList2(3,[1,8,3,2,6])
Searching a list is so common that Python provides a built-in mechanism for it. Try each of the following.
-
3 in [1,8,2,6]
-
3 in [1,8,3,2,6]
-
3 not in [1,8,2,6]
-
3 not in [1,8,3,2,6]
For another example, let's return to a previous example of computing the product of a list of numbers. Our previous code looked like the following.
-
def productList(numbers): product = 1 for number in numbers: product = product * number return product productList([3,6,4,1,2,8,3]) productList([3,6,4,1,0,2,8,3])
While that works just fine, imagine that your list is really long. If there is just a single zero in the list, the product will be zero, and it could be a waste of time to multiply all those numbers. Instead, we could just stop when we found a zero. (We typically want to pick the fastest algorithm to accomplish our goal. Not only does it save the computer time, but it saves us time, as we wait for the answer. We'll talk more about this later.)
The following is one way to accomplish this idea. This function also shows us a count of how many numbers it looked at, so we can see the difference.
-
def productList(numbers): product = 1 count = 0 for number in numbers: product = product * number count = count + 1 if product == 0: break print "Looked at ", count, " items out of ", len(numbers), " to compute the product ", product return product productList([3,6,4,1,2,8,3]) productList([3,6,4,1,0,2,8,3])
Both return
and break
provide ways to exit
from some code.
To exit from a function, use return
.
To exit from a loop, use break
.