Lesson 07 - If Statements

The following topics are discussed in this notebook:

  • If statements
  • If-Else statements
  • If-Elif-Else statements
  • If statements and loops

Additional Resources

Basic If Statments

We can use if statements (also called conditionals) to control how or if portions of our code will execute, based on conditions that we provide.

In [1]:
age = 17

if age < 21:
    print("You are too young to drink.")
You are too young to drink.
In [2]:
names = ["Alex", "Beth", "Craig", "Drew", "Emma", "Fiona"]
ages = [19, 17, 24, 18, 21, 30]

for i in range(0, len(names) ):
    if ages[i] < 21:
        print( names[i] + " is too young to drink.")
Alex is too young to drink.
Beth is too young to drink.
Drew is too young to drink.

If-Else Statements

In [3]:
names = ["Alex", "Beth", "Craig", "Drew", "Emma", "Fiona"]
ages = [19, 17, 24, 18, 21, 30]

for i in range(0, len(names) ):
    
    if ages[i] < 21:
        print( names[i] + " is too young to drink.")
    else:
        print( "Bottoms up, " + str(names[i] + "!"))
Alex is too young to drink.
Beth is too young to drink.
Bottoms up, Craig!
Drew is too young to drink.
Bottoms up, Emma!
Bottoms up, Fiona!

� Exercise

The modulus % is a mathematical operator that can be used to test for divisibilitiy. The expression a % b returns the remainder of a after division by b. If that remainder is 0, then that means that a is divisible by b.

For example:

In [4]:
print( 27 % 3 == 0)
print( 17 % 3 == 0)
True
False

A list of randomly generated integers is provided below. Write a loop that returns one of the following phrases for each element of rList:

[x] is even.
[x] is odd.
In [5]:
rList = [74, 55, -77, 58, 0, 91, 62, 31, -91, 61, -6, 12, 0, -73, 16, 53, -28, -4, 88, 8]

for i in range(0, len(rList)):
    if rList[i] % 2 == 0:
        print(str(rList[i]) + " is even.")
    else:
        print(str(rList[i]) + " is odd.")
74 is even.
55 is odd.
-77 is odd.
58 is even.
0 is even.
91 is odd.
62 is even.
31 is odd.
-91 is odd.
61 is odd.
-6 is even.
12 is even.
0 is even.
-73 is odd.
16 is even.
53 is odd.
-28 is even.
-4 is even.
88 is even.
8 is even.

If-Elif-Else Statements

In [6]:
for i in range(0, len(rList)):
    
    if rList[i] < 0:
        print(str(rList[i]) + " is negative.")
    elif rList[i] > 0:
        print(str(rList[i]) + " is positive.")
    else:
        print(str(rList[i]) + " is neither positive nor negative.")
74 is positive.
55 is positive.
-77 is negative.
58 is positive.
0 is neither positive nor negative.
91 is positive.
62 is positive.
31 is positive.
-91 is negative.
61 is positive.
-6 is negative.
12 is positive.
0 is neither positive nor negative.
-73 is negative.
16 is positive.
53 is positive.
-28 is negative.
-4 is negative.
88 is positive.
8 is positive.

� Exercise

Two lists are given below. One provides a list of names. The other provides a list of credit scores associated with each of the people in the first list. Assume that credit scores are classified as follows:

  • 0 - 649 is considered "poor".
  • 650 - 699 is considered "fair".
  • 700 and up is considered "good".

For each of the names in the list, print a statement of the following form:

[name] has a [poor/fair/good] credit score. 
In [7]:
names = ["Alex", "Beth", "Craig", "Drew", "Emma", "Fiona"]
credit = [683, 580, 752, 607, 615, 703]

for i in range(0, len(names)):
    
    if(credit[i] <= 649):
        print(names[i] + " has a poor credit score.")
    elif(credit[i] <= 699):
        print(names[i] + " has a fair credit score.")
    else:
        print(names[i] + " has a good credit score.")
Alex has a fair credit score.
Beth has a poor credit score.
Craig has a good credit score.
Drew has a poor credit score.
Emma has a poor credit score.
Fiona has a good credit score.

� Exercise

We can include as many elif statements as we would like.

Assume that we have the following, more specific, classification of credit scores:

  • 0 - 599 is considered "bad".
  • 600 - 649 is considered "poor".
  • 650 - 699 is considered "fair".
  • 700 - 749 is considered "good".
  • 750 and up is considered "excellent".

Modify the code from above to reflext this new classification system.

In [8]:
for i in range(0, len(names)):
    
    if(credit[i] <= 599):
        print(names[i] + " has a bad credit score.")
    elif(credit[i] <= 649):
        print(names[i] + " has a poor credit score.")
    elif(credit[i] <= 699):
        print(names[i] + " has a fair credit score.")
    elif(credit[i] <= 749):
        print(names[i] + " has a good credit score.")
    else:
        print(names[i] + " has a excellent credit score.")
Alex has a fair credit score.
Beth has a bad credit score.
Craig has a excellent credit score.
Drew has a poor credit score.
Emma has a poor credit score.
Fiona has a good credit score.

Using Conditional Statements to Avoid Errors

When Python encounters an error, it stops executing statements. We would like our code to be robust so that unexpected inputs do not cause our programs to stop executing prematurely. If statements can help us to avoid situations that would result in errors, thus breaking our code.

We will illustrate this idea using the factorial funtion from the math package. We begin by importing this package.

In [9]:
import math

In the cell below, we would define a list of values. Our goal is to calculate the factorial of every whole number in this list.

In [10]:
myList = [4, 3.0, 2.7, 7, 'one', 5]

We will loop through myList, attempting to print the factorial of each element.

In [11]:
for i in range(0, len(myList)):
    print(math.factorial(myList[i]))
24
6
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-c112b0404cec> in <module>()
      1 for i in range(0, len(myList)):
----> 2     print(math.factorial(myList[i]))

ValueError: factorial() only accepts integral values

The loop executed correctly for the first two elements in the list. However, once it hit the element 2.7, it threw an error and stopped executing. Factorials can only be calculated for whole numbers.

We can correct this behavior by using conditional statements.

In [ ]:
for i in range(0, len(myList)):
    if(type(myList[i]) == int):
        print(math.factorial(myList[i]))
    else:
        print(str(myList[i]) + " is not a whole number.")

� Exercise

The factorial of the second element did not print. Can we fix this?

In [ ]:
int(myList[i]) == myList[i]

for i in range(0, len(myList)):
    if(type(myList[i]) == int):
        print(math.factorial(myList[i]))
    elif( type(myList[i]) == float and int(myList[i]) == myList[i]):
        print(math.factorial(myList[i]))
    else:
        print(str(myList[i]) + " is not a whole number.")