Week 3, Monday: branching, boolean type


Here's a simple example that shows branching in a program:

$ python adventure.py 

  You are in a dimly lit computer room. A lab that is worth
  50% of your grade is due in 4 hours. What do you want
  to do?

    1 Start work on your lab
    2 Go play ultimate frisbee with your friends
    3 Take a nap on the CS couches

          ---> 3


  You wake up with bad hair.
  The lab is due in 1 hour. What do you want to do?

    1 Go back to sleep
    2 Call your professor and ask for more time
    3 Start work on your CS homework

          ---> 1

You die a horrible death.
Your CS professor doesn't even realize
you are no longer coming to class... :(

Presumably, if I made better choices, the outcome would be better.

To accomplish something like that, we want to say something like "if this condition is True, do this, otherwise, do that". And this is exactly how the if/else syntax in python looks:

if some-condition-is-True:
  do this block of code
  do this block of code

Where, as before, a block of code can be one or more lines, and must all be indented.

What we don't know yet is how to create or evaluate the condition. For that we need a new type!

the boolean type

Named after George Boole, the boolean type consists of just two values: True and False. And to create the conditions we need for branching, we often use comparison operators:

>>> x = 5       # assignment
>>> x > 0       # greater than
>>> x < 0       # less than
>>> x == 0      # equal to (note the 2 equals signs)
>>> x <= 5      # less than or equal to
>>> x >= 5      # greater than or equal to
>>> x != 5      # not equal to

Also note, both True and False are capitalized.

membership operator

Python also has the in operator, which tells if something is a member of a given sequence. Here are some simple examples:

>>> L = list("abcdefg")
>>> print(L)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> "A" in L
>>> "a" in L
>>> "X" not in L

>>> S = "Swarthmore"
>>> "A" in S
>>> "a" in S
>>> "wart" in S
>>> S > "Harvard"

speeding ticket

Here's a simple if/else branch example:

def main():

  limit = 55
  speed = int(raw_input("How fast were you going? "))

  if speed <= limit:
    print("OK...off you go.")
    print("That's too fast!!!")
    print("Here's your ticket...")

So the condition used is speed <= limit, which evaluates to either True or False. If True, the first if block is executed. If False, the else block is executed.


As with for loops, a code block can contain any valid python code, so it's possible to have a for loop in an if block, or another if block nested inside the first if block, or one for loop nested inside another for loop.

more than two branches

If you have more than two branches, you can have one or more elif branches. For example, if you were a professor, writing a program to assign grades, you might need one branch for the A's, one for the B's, and so on. Here is one way to write that program, assuming you have the numberical grade stored in a variable called grade:

if grade >= 90:
elif grade >= 80:
elif grade >= 70:
elif grade >= 60:

Your Turn!

Can you write this program?

$ python gtw.py 
Would you like to play Global Thermonuclear War? y

<large explosion>......you LOSE!

$ python gtw.py 
Would you like to play Global Thermonuclear War? Y

<large explosion>......you LOSE!

$ python gtw.py 
Would you like to play Global Thermonuclear War? n

The only winning move is not to play. 

$ python gtw.py 
Would you like to play Global Thermonuclear War? pony

How about a nice game of chess?

Notice how it has 3 branches, but also accepts at least two different answers for "yes". Can you think of a way to accept all of these for "yes"? ["y","yes","sure","Y","Yes","YES"]