branching and conditionals

Try the Jupyter notebook version.

motivation

Most programs have more than one branch, meaning they can do different things, depending on some condition (e.g., did the user click on the Home button, or the Print button?).

Here is a silly example:

$ python3 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.

syntax

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
else:
    do this block of code

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
True
>>> x < 0       # less than
False
>>> x == 0      # equal to (note the 2 equals signs)
False
>>> x <= 5      # less than or equal to
True
>>> x >= 5      # greater than or equal to
True
>>> x != 5      # not equal to
False
>>> "jeff" > "ameet"    # can compare strings, too!
True

Also note, both True and False are capitalized.

the membership operator: in

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
False
>>> "a" in L
True
>>> "X" not in L
True

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

examples

Here's a simple if/else branch example:

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

if speed <= limit:
    print("OK...off you go.")
else:
    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.

nesting

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:
    print("A")
elif grade >= 80:
    print("B")
elif grade >= 70:
    print("C")
elif grade >= 60:
    print("D")
else:
    print("F")

challenge

Ask the user for a string and a letter. Then tell the user how many of that letter are in the string:

$ python3 lettercount.py 
phrase: we love comp sci!!
letter: o
There are 2 o's in that phrase.

How about this program?

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

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

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

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

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

The only winning move is not to play. 
                         --JOSHUA

$ python3 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 ("y","yes","sure","Y","Yes","YES") for "yes"?


CS21 Topics