If Statements

By allowing you to respond selectively to different situations and conditions, if statements open up whole new possibilities for your programs. In this section, you will learn how to test for certain conditions, and then respond in appropriate ways to those conditions.

What is an if statement?

An if statement tests for a condition, and then responds to that condition. If the condition is true, then whatever action is listed next gets carried out. You can test for multiple conditions at the same time, and respond appropriately to each condition.

Example

Here is an example that shows a number of the desserts I like. It lists those desserts, but lets you know which one is my favorite.

In [2]:
# A list of desserts I like.
desserts = ['ice cream', 'chocolate', 'apple crisp', 'cookies']
favorite_dessert = 'apple crisp'

# Print the desserts out, but let everyone know my favorite dessert.
for dessert in desserts:
    if dessert == favorite_dessert:
        # This dessert is my favorite, let's let everyone know!
        print("%s is my favorite dessert!" % dessert.title())
    else:
        # I like these desserts, but they are not my favorite.
        print("I like %s." % dessert)
I like ice cream.
I like chocolate.
Apple Crisp is my favorite dessert!
I like cookies.

What happens in this program?

  • The program starts out with a list of desserts, and one dessert is identified as a favorite.
  • The for loop runs through all the desserts.
  • Inside the for loop, each item in the list is tested.
    • If the current value of dessert is equal to the value of favorite_dessert, a message is printed that this is my favorite.
    • If the current value of dessert is not equal to the value of favorite_dessert, a message is printed that I just like the dessert.

You can test as many conditions as you want in an if statement, as you will see in a little bit.

top

Logical Tests

Every if statement evaluates to True or False. True and False are Python keywords, which have special meanings attached to them. You can test for the following conditions in your if statements:

Whitespace

Remember learning about PEP 8? There is a section of PEP 8 that tells us it's a good idea to put a single space on either side of all of these comparison operators. If you're not sure what this means, just follow the style of the examples you see below.

Equality

Two items are equal if they have the same value. You can test for equality between numbers, strings, and a number of other objects which you will learn about later. Some of these results may be surprising, so take a careful look at the examples below.

In Python, as in many programming languages, two equals signs tests for equality.

Watch out! Be careful of accidentally using one equals sign, which can really throw things off because that one equals sign actually sets your item to the value you are testing for!

In [3]:
5 == 5
Out[3]:
True
In [4]:
3 == 5 
Out[4]:
False
In [24]:
5 == 5.0
Out[24]:
True
In [8]:
'eric' == 'eric'
Out[8]:
True
In [9]:
'Eric' == 'eric'
Out[9]:
False
In [10]:
'Eric'.lower() == 'eric'.lower()
Out[10]:
True
In [11]:
'5' == 5
Out[11]:
False
In [12]:
'5' == str(5)
Out[12]:
True

top

Inequality

Two items are inequal if they do not have the same value. In Python, we test for inequality using the exclamation point and one equals sign.

Sometimes you want to test for equality and if that fails, assume inequality. Sometimes it makes more sense to test for inequality directly.

In [13]:
3 != 5
Out[13]:
True
In [14]:
5 != 5
Out[14]:
False
In [18]:
'Eric' != 'eric'
Out[18]:
True

top

Other Inequalities

greater than

In [16]:
5 > 3
Out[16]:
True

greater than or equal to

In [19]:
5 >= 3
Out[19]:
True
In [20]:
3 >= 3
Out[20]:
True

less than

In [21]:
3 < 5
Out[21]:
True

less than or equal to

In [22]:
3 <= 5
Out[22]:
True
In [23]:
3 <= 3
Out[23]:
True

top

Checking if an item is in a list

You can check if an item is in a list using the in keyword.

In [25]:
vowels = ['a', 'e', 'i', 'o', 'u']
'a' in vowels
Out[25]:
True
In [26]:
vowels = ['a', 'e', 'i', 'o', 'u']
'b' in vowels
Out[26]:
False

Exercises

True and False

  • Write a program that consists of at least ten lines, each of which has a logical statement on it. The output of your program should be 5 Trues and 5 Falses.
  • Note: You will probably need to write print(5 > 3), not just 5 > 3.

top

The if-elif...else chain

You can test whatever series of conditions you want to, and you can test your conditions in any combination you want.

Simple if statements

The simplest test has a single if statement, and a single statement to execute if the condition is True.

In [27]:
dogs = ['willie', 'hootz', 'peso', 'juno']

if len(dogs) > 3:
    print("Wow, we have a lot of dogs here!")
Wow, we have a lot of dogs here!

In this situation, nothing happens if the test does not pass.

In [28]:
###highlight=[2]
dogs = ['willie', 'hootz']

if len(dogs) > 3:
    print("Wow, we have a lot of dogs here!")

Notice that there are no errors. The condition len(dogs) > 3 evaluates to False, and the program moves on to any lines after the if block.

if-else statements

Many times you will want to respond in two possible ways to a test. If the test evaluates to True, you will want to do one thing. If the test evaluates to False, you will want to do something else. The if-else structure lets you do that easily. Here's what it looks like:

In [30]:
dogs = ['willie', 'hootz', 'peso', 'juno']

if len(dogs) > 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Wow, we have a lot of dogs here!

Our results have not changed in this case, because if the test evaluates to True only the statements under the if statement are executed. The statements under else area only executed if the test fails:

In [31]:
###highlight=[2]
dogs = ['willie', 'hootz']

if len(dogs) > 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Okay, this is a reasonable number of dogs.

The test evaluated to False, so only the statement under else is run.

if-elif...else chains

Many times, you will want to test a series of conditions, rather than just an either-or situation. You can do this with a series of if-elif-else statements

There is no limit to how many conditions you can test. You always need one if statement to start the chain, and you can never have more than one else statement. But you can have as many elif statements as you want.

In [32]:
dogs = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Holy mackerel, we might as well start a dog hostel!

It is important to note that in situations like this, only the first test is evaluated. In an if-elif-else chain, once a test passes the rest of the conditions are ignored.

In [33]:
###highlight=[2]
dogs = ['willie', 'hootz', 'peso', 'monty']

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Wow, we have a lot of dogs here!

The first test failed, so Python evaluated the second test. That test passed, so the statement corresponding to len(dogs) >= 3 is executed.

In [34]:
###highlight=[2]
dogs = ['willie', 'hootz']

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Okay, this is a reasonable number of dogs.

In this situation, the first two tests fail, so the statement in the else clause is executed. Note that this statement would be executed even if there are no dogs at all:

In [35]:
###highlight=[2]
dogs = []

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
else:
    print("Okay, this is a reasonable number of dogs.")
Okay, this is a reasonable number of dogs.

Note that you don't have to take any action at all when you start a series of if statements. You could simply do nothing in the situation that there are no dogs by replacing the else clause with another elif clause:

In [36]:
###highlight=[8]
dogs = []

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
elif len(dogs) >= 1:
    print("Okay, this is a reasonable number of dogs.")

In this case, we only print a message if there is at least one dog present. Of course, you could add a new else clause to respond to the situation in which there are no dogs at all:

In [37]:
###highlight=[10,11]
dogs = []

if len(dogs) >= 5:
    print("Holy mackerel, we might as well start a dog hostel!")
elif len(dogs) >= 3:
    print("Wow, we have a lot of dogs here!")
elif len(dogs) >= 1:
    print("Okay, this is a reasonable number of dogs.")
else:
    print("I wish we had a dog here.")
I wish we had a dog here.

As you can see, the if-elif-else chain lets you respond in very specific ways to any given situation.

Exercises

Three is a Crowd

  • Make a list of names that includes at least four people.
  • Write an if test that prints a message about the room being crowded, if there are more than three people in your list.
  • Modify your list so that there are only two people in it. Use one of the methods for removing people from the list, don't just redefine the list.
  • Run your if test again. There should be no output this time, because there are less than three people in the list.
  • Bonus: Store your if test in a function called something like crowd_test.

Three is a Crowd - Part 2

  • Save your program from Three is a Crowd under a new name.
  • Add an else statement to your if tests. If the else statement is run, have it print a message that the room is not very crowded.

Six is a Mob

  • Save your program from Three is a Crowd - Part 2 under a new name.
  • Add some names to your list, so that there are at least six people in the list.
  • Modify your tests so that
    • If there are more than 5 people, a message is printed about there being a mob in the room.
    • If there are 3-5 people, a message is printed about the room being crowded.
    • If there are 1 or 2 people, a message is printed about the room not being crowded.
    • If there are no people in the room, a message is printed abou the room being empty.

top

More than one passing test

In all of the examples we have seen so far, only one test can pass. As soon as the first test passes, the rest of the tests are ignored. This is really good, because it allows our code to run more efficiently. Many times only one condition can be true, so testing every condition after one passes would be meaningless.

There are situations in which you want to run a series of tests, where every single test runs. These are situations where any or all of the tests could pass, and you want to respond to each passing test. Consider the following example, where we want to greet each dog that is present:

In [38]:
dogs = ['willie', 'hootz']

if 'willie' in dogs:
    print("Hello, Willie!")
if 'hootz' in dogs:
    print("Hello, Hootz!")
if 'peso' in dogs:
    print("Hello, Peso!")
if 'monty' in dogs:
    print("Hello, Monty!")
Hello, Willie!
Hello, Hootz!

If we had done this using an if-elif-else chain, only the first dog that is present would be greeted:

In [41]:
###highlight=[6,7,8,9,10,11]
dogs = ['willie', 'hootz']

if 'willie' in dogs:
    print("Hello, Willie!")
elif 'hootz' in dogs:
    print("Hello, Hootz!")
elif 'peso' in dogs:
    print("Hello, Peso!")
elif 'monty' in dogs:
    print("Hello, Monty!")
Hello, Willie!

Of course, this could be written much more cleanly using lists and for loops. See if you can follow this code.

In [43]:
dogs_we_know = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']
dogs_present = ['willie', 'hootz']

# Go through all the dogs that are present, and greet the dogs we know.
for dog in dogs_present:
    if dog in dogs_we_know:
        print("Hello, %s!" % dog.title())
Hello, Willie!
Hello, Hootz!

This is the kind of code you should be aiming to write. It is fine to come up with code that is less efficient at first. When you notice yourself writing the same kind of code repeatedly in one program, look to see if you can use a loop or a function to make your code more efficient.

top

True and False values

Every value can be evaluated as True or False. The general rule is that any non-zero or non-empty value will evaluate to True. If you are ever unsure, you can open a Python terminal and write two lines to find out if the value you are considering is True or False. Take a look at the following examples, keep them in mind, and test any value you are curious about. I am using a slightly longer test just to make sure something gets printed each time.

In [60]:
###highlight=[2]
if 0:
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to False.
In [61]:
###highlight=[2]
if 1:
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to True.
In [62]:
###highlight=[2,3]
# Arbitrary non-zero numbers evaluate to True.
if 1253756:
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to True.
In [63]:
###highlight=[2,3]
# Negative numbers are not zero, so they evaluate to True.
if -1:
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to True.
In [64]:
###highlight=[2,3]
# An empty string evaluates to False.
if '':
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to False.
In [66]:
###highlight=[2,3]
# Any other string, including a space, evaluates to True.
if ' ':
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to True.
In [67]:
###highlight=[2,3]
# Any other string, including a space, evaluates to True.
if 'hello':
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to True.
In [68]:
###highlight=[2,3]
# None is a special object in Python. It evaluates to False.
if None:
    print("This evaluates to True.")
else:
    print("This evaluates to False.")
This evaluates to False.

top

Overall Challenges

Alien Points

  • Make a list of ten aliens, each of which is one color: 'red', 'green', or 'blue'.
    • You can shorten this to 'r', 'g', and 'b' if you want, but if you choose this option you have to include a comment explaining what r, g, and b stand for.
  • Red aliens are worth 5 points, green aliens are worth 10 points, and blue aliens are worth 20 points.
  • Use a for loop to determine the number of points a player would earn for destroying all of the aliens in your list.
  • hint

top

Hints

These are placed at the bottom, so you can have a chance to solve exercises without seeing any hints.

Alien Invaders

  • After you define your list of aliens, set a variable called current_score or current_points equal to 0.
  • Inside your for loop, write a series of if tests to determine how many points to add to the current score.
  • To keep a running total, use the syntax current_score = current_score + points, where points is the number of points for the current alien.