Lecture 11 - Decisions

Lecture Date: Friday, February 12

Programs that start and then end without any choices to make are boring. If we are going to write a program to do anything interesting, it has to be able to make decisions based on the data it is seeing.

Enter the if statement.

Consider this situation:

ifstatement.png

Pretty straight forward. But how do we make the computer do something different based on the input?

First, how do we decide whether it is cold outside or not?

Well, we could ask the user:

Ask the User
1
temp = input("What is the temperature outside?: ")

This is good, but this doesn’t yet tell us whether it is specifically cold or not. And that’s different for everyone. So let’s add this:

What is cold?
1
cold_threshold = 30

So, now let’s test whether it is cold or not!

Is it cold?
1
2
3
4
if temp <= cold_threshold:
  wear_coat()
  wear_hat()
  wear_gloves()

There’s another way we could do this - and that’s with what’s called a flag variable. A flag variable is a bool that we use to determine some sort of state. In this case, we would write it like this:

Is it cold?
1
2
3
4
5
6
7
8
9
10
11
is_cold = False

if temp <= cold_threshold:
  is_cold = True


if is_cold:
  wear_coat()
  wear_hat()
  wear_gloves()
  

This makes the code a bit more readable, and is_cold can be easily reused later on.

Now, what if we had to make more of a decision here:

ifelsestatement.png

We could use our flag variable again, but now we will add another option to our if statement:

Is it cold?
1
2
3
4
5
6
7
8
9
10
is_cold = False;

if temp <= cold_threshold:
  is_cold = True

if is_cold:
  wear_coat()

else:
  wear_shorts()

In this case, we must do one or the other. A simple if statement either will or will not execute. Here, if the if is not executed, then the else will be.

We can string more of these together as well!

Is it cold?
1
2
3
4
5
6
7
8
if is_cold:
  wear_coat()
  
elif today_is_sunday:
  wear_blazer()

else:
  wear_shorts()

Now you are guaranteed to execute one of these three paths.

Other points for today:

  • How to indent your code properly
  • Relational operators (<, >, ==, >=, <=, !=)
  • Nested if statements
  • How to test for your letter grade in the class