IF Statements

Much of our lives are spent asking questions in order to figure out what we should be doing next. For example, we may ask a friend, "Is it time for lunch?" If his answer is "Yes," the next things we'll likely be doing is eating lunch. If his answer is "No," we'll be doing something else next — in fact, oftentimes, we'll just continue doing whatever it was we were doing before we asked the question!

As another example, you might ask a friend, "Do you want to see a movie today?" If he says, "Sure," you'll probably next spend some time figuring out what movie to see. But, if he says, "Nah, I'd rather go play in the park," the rest of your day will probably go much differently.

Programming is very similar — we often ask a lot of questions in our software to determine what we should do next. For example, when you push a button on your television remote control, it sends a signal to your TV telling the TV to change the station or adjust the volume. But, what you probably don't realize is that this works because many times per second, the software in your TV is asking, "Did someone just press a button on the remove control?"

Most of the time the answer is "No," so the TV software moves onto something else for short period of time (likely whatever else it was already doing). But, if the answer is "Yes" (in other words, if you were pressing a button on the remote), the TV will then take action to determine what button was pressed and then carry out the request.

The most basic way for software to ask and respond to a question is by using what is known as an if statement. An if statement asks a True or False question, and based on the answer, takes the appropriate action.

As another example, let's say we have a circuit that contains a thermometer and sends the current temperature back to computer every once in a while. Next, let's assume that we use a variable named temperature to store the data the thermometer sends us. Finally, let's pretend that the most recent temperature sent to us by the thermometer is 95 degrees. This is represented by our variable like this:

The software might then use an if statement to evaluate the temperature and comment on it if it's over 90 degrees:

Note: The > sign is called an operator, and it means "Greater Than" — we'll talk about how this, and many other operators, work later in this tutorial.

Now, type these three lines into your code window, run the program and see what happens:

If you run the program, you'll see that the computer prints, "Wow, it's hot out there!" in your output window. In this case, the computer evaluated the statement (temperature > 90), determined that the statement was True (the temperature is 95, which is over 90) and then took the specified action based on the fact that the statement was True.

But, what if the code determined that the statement were False? For example, give this piece of code a try:

In this case, the temperature is still defined as 95 degrees, but this time, we're asking if the temperature is less than 90. The answer to that question is False (the temperature is not less than 90). And because the statement is False, the action following the if statement is not executed, and nothing is printed to the screen.

We typically call the evaluation line a "conditional statement," call the comparison the "condition" and call the action commands after the conditional statement the "code block."

So, in this case, the following is the conditional statement:

  if temperature < 90:

The following is the condition:

  temperature < 90

And this is the code block:

  print("Okay, it's not too hot out there.")

We'll be using those terms from here on out.

Now, let's discuss some additional features of conditional statements and code blocks…

Comparison Operators

In the above examples, we used the symbols > and < in our conditional statements. We used > to ask the question, "Is the first value greater than the second value?" And, we used the symbol < to ask the question "Is the first value less than the second value?"

These are just two of several symbols (we call them "operators") that can be used to compare values in a conditional statement. Here is the list of the most common comparison operators:

OPERATOR

DEFINITION

==

Is Equal To?

!=

Is Not Equal To?

>

Is Greater Than?

<

Is Less Than?

>=

Is Greater Than or Equal To?

<=

Is Less Than or Equal To?

Let's look at some examples…but first, let's define a couple variables to use in our examples:

Now for our examples:

my_dogs_age == 4 would evaluate as True

my_age != 43 would evaluate as False

my_age > my_dogs_age would evaluate as True

my_age < my_dogs_age would evaluate as False

my_dogs_age >= 4 would evaluate as True

my_age <= 35 would evaluate as False

Note: Keep in mind that = and == are very different in programming. The = sign tells the computer that we're assigning the value of one thing (whatever is on the right side of the = sign) to another thing (the variable on the left side of the = sign). But, the == asks the computer whether two things are equal, and returns a True (if they are equal) or a False (if they are not equal).

Complex Conditions

Code Blocks

In all the examples so far in this chapter, our code blocks have consisted of a single line of code. For example, in this piece of code:

our code block was a single print statement.

But, in many situations, after evaluating a conditional, we're going to want to take action that requires many commands, not just one. For this reason, code blocks can be any number of commands following a conditional statement. Our example above could be changed to:

In this example, we have two print statements in our code block. Notice that both commands are indented the exact same amount — this is how the computer knows that all the lines are part of the same code block. It's very important that you use the same number of spaces or tabs for every line of the code block, or your code will not function as you expect (and may not function at all). And, space and tab characters are different, even though it is hard to tell as they are both invisible. You must stick with all spaces or all tabs, not both. All the code examples in this guide use tabs, not spaces, so we suggest you do the same.

Compound Conditional Statements

In some situations, you may find that you need to have more complex conditional statements in your code than just a single comparison. When that need arises, we can use compound conditional statements, which is really just a fancy way of saying that we can put multiple comparisons together into a single conditional statement.

For example, in the previous section, we used the condition:

  temperature < 90

to determine if it was less than 90 degrees outside.

But, what if we didn't just want to know if the temperature was less than 90 degrees — we wanted to know whether the temperature was between 80 and 90 degrees? That would actually require two different conditions:

  temperature > 80
  temperature < 90

We can create a compound conditional statement that will check both of those comparisons before taking any action, as follows:

The and keyword tells the computer that both statements must be True in order for the entire compound conditional statement to be True.

What if we only cared about the situation where the temperature was less than 80 degrees or more than 90 degrees? We can create a compound conditional statement to do this as well:

In this case, the or keyword tells the computer that either one or both of the statements must be True in order for the entire compound conditional statement to be True.

Any number or combination of and and or keywords can be used to combine conditional statements.

Finally, the not keyword works just like not in English — it tests if the opposite of a condition is True. For example, the following if statements are written differently, but test the same exact thing:

Adding ELSE

IF/ELSE Statements

In our previous examples, we evaluated a conditional, and took action if the result of the evaluation was True. But, in many cases, we also want to take action when the result of the evaluation is False, in addition to when it's True.

For example, perhaps we don't just want to let the user know if the temperature is over 90 degrees, but we also want to let the user know if the temperature is under 90 degrees:

We use the else: keyword to indicate what action should be taken if the conditional statement evaluates to False. We are basically telling the computer:

If the conditional statement is true, do this. Otherwise (else), do that.

ELIF Statements

There are going to be some cases where, "If true, do this. If false, do that," just isn't enough to provide the functionality you need.

For example, perhaps we want to know more than whether the temperature is above or below 90 degrees? Perhaps we want to know if it's below 60 degrees? Or in the 60s? Or in the 70s? Or in the 80s? Or in the 90s? Or above 90 degrees?

In the case where you want to test for many different conditions, you can use the elif ("else if") statement. Like this: