19  Python if/else (flow of control)

Flow of control is about how we move through a program. We cover if/else statements; later we learn about iteration (for loops). You can copy each code snippets below into a notebook and run it. Then you can follow along with the recorded lecture or experiment yourself.

"""A short script to demonstrate branching."""
# No branching

destination = "home"

print("Done with work, I'm off {}".format(destination))

But often we want to execute only some lines of the code, depending on the content of a variable.

##############
# One branch
#############

day = "Friday"

# Is it Friday yet?
if (day == "Friday"):
    destination = "bar"
else:
    destination = "gym"

print("Done with work, I'm off {}".format(destination))

We can combine this, taking a branch inside another branch, leading to three possible outcomes.

##########
# Two branches
##########

day = "Wednesday"

# Is it Friday yet?
if (day == "Friday"):
    destination = "bar"
else:
    if (day == "Wednesday"):
        destination = "Park"
    else:
        destination = "gym"

print("Done with work, I'm off {}".format(destination))

We could split off even further. Examine the code below and draw a picture similar to the others on this page.

day = "Wednesday"

# Is it Friday yet?
if (day == "Friday"):
    destination = "bar"
else:
    if (day == "Wednesday"):
        destination = "Park"
    else:
        if (day == "Tuesday"):
            destination = "Sleep"
        else:
            destination = "gym"

print("Done with work, I'm off {}".format(destination))

When we’re mapping options in this way we can simplify the syntax using the elif construct.

##########
# Two branches, a little less indentation, using "elif"
##########

day = "Wednesday"

# Is it Friday yet?
if (day == "Friday"):
    destination = "bar"
elif (day == "Wednesday"):
    destination = "Park"
else:
    destination = "gym"

print("Done with work, I'm off {}".format(destination))

There is also a screencast from a previous semester that covers the if/else material. It doesn’t use notebooks but it uses the same code: Flow of Control Screencast.

19.1 Assignment or Comparison?

Note the difference between a single = and double ==. The single = is the “Assignment operator” and puts things into variables. The double == is the “comparison operator” and tests whether things are the same. A double == returns either True or False. You don’t want to have a = in the parens for an if statement.

19.2 The colon starts a “block” of code

Can you see the colon at the end of the if and the else lines? The colon starts a section of code, called a “block”. It’s easy to forget the colon!

if (day == "Friday"):
    destination = "bar"
else:
    destination = "gym"

After the colon comes an indent, we will use 4 spaces (following the Python style guide called PEP8). The block ends when we return to the previous indent level. So know you know what it means for code to be “in” the if block or “in” the else block.

19.3 Three principles of programming

  1. The computer is a “literal idiot”. Sadly, we must expect errors as we type our code. Error messages are often not particularly helpful. Success in fixing an error often produces a new error! We have to learn to celebrate “getting past” a fixed typo to find the new error.

  2. Programmers “play the code in their heads”. We have to be able to read the code and predict what will happen. Like playing a video game with our eyes closed. We need to be able to understand the “number of steps” the computer is going to take. We can use print statements to check the value of variables to confirm our predictions.

  3. The “principle of replacement”. When we see a variable name, we “look through” the name and see it’s contents. It is exactly as if the content of the variable were explicitly typed into the code. Code that shows an Operations (like putting together strings with the + character) are replaced with the result of the operation.

long_string = "first part" + " second part"

resolves to

long_string = "first part second part"

and

long_string.upper()

we “see through” the long_string variable so it resolves to

"first part second part".upper()