Lesson 10 - Conditional Statements

The following topics are discussed in this notebook:

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

Conditional Statements

We can use conditional statements to control how or if portions of our code will execute, based on logical criteria that we provide. The most basic type of conditional statement is an if statement. The syntax for an if statement is as follows:

if condition:
    code to be executed if condition is true
In [1]:
grade = 34

if grade >= 60:
    print('You passed the exam.')
    print('Congratulations!')

If-Else Statements

We can use an if statemnt to determine whether or not a particular set of actions will be satisfied. But we will occasionally want to use a condition to determine which of two sets of actions will be completed. This functionality is provided to us by an if-else statement. The syntax for an if-else statement is as follows:

if condition:
    code to be executed if condition is true
else:
    code to be executed if condition is false
In [2]:
grade = 34

if grade >= 60:
    print("You passed the exam.")
    print("Congratulations!")
else:
    print("You failed the exam.")
    print("Better luck next time.")
You failed the exam.
Better luck next time.

If-Elif-Else Statements

If statements allow us to determine whether or not a single set of actions will be taken, and if-else statments allow us to determine which of two sets of actions will be taken. If we require our program to select from more than two options when making a decision, we can use an if-elif-else statment. The syntax for this sort of statement is as follows:

if condition1:
    code to be executed if condition is true
elif condition2:  
    code to be executed if condition1 is false, but condition2 is true
elif condition3:  
    code to be executed if all above conditions are false, but condition3 is true
elif condition4:  
    code to be executed if all above conditions are false, but condition4 is true
...
else:
    code to be executed if all above conditions are false. 

We can include as many conditions as we would like in an if-elif-else statement. However, It is important to note that only one portion of the code will be allowed to execute. It is possible that multiple conditions might potentially evaluate to True, but as soon as the if-elif-else statement encounters its first True condition, it will execute the code for that condition, and will then skip the rest of the statment.

The example below provides an example with a single elif clause.

In [3]:
grade = 85

if grade >= 90:
    print("You got an 'A' on the exam.")
elif grade >= 80:
    print("You got a 'B' on the exam.")
elif grade >= 70:
    print("You got a 'C' on the exam.")
elif grade >= 60:
    print("You got a 'D' on the exam.")
else:
    print("You got an 'F' on the exam.")
You got a 'B' on the exam.

Conditional Statements and Loops

We will often use if statements in conjunctions with loops. In the example below, we are provided with two lists, one that contains the names of several students, and one that contains the grades that these students got on an exam. We will loop over these lists, printing a different message for each student.

In [4]:
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', 'Fred']
grades = [56, 92, 87, 43, 75, 62]

for i in range(0, len(names) ):
    
    if grades[i] >= 90:
        print(names[i] + " got a grade of 'A' on the exam.")
    elif grades[i] >= 80:
        print(names[i] + " got a grade of 'B' on the exam.")
    elif grades[i] >= 70:
        print(names[i] + " got a grade of 'C' on the exam.")
    elif grades[i] >= 60:
        print(names[i] + " got a grade of 'D' on the exam.")
    else:
        print(names[i] + " got a grade of 'F' on the exam.")
    
Anna got a grade of 'F' on the exam.
Beth got a grade of 'A' on the exam.
Chad got a grade of 'B' on the exam.
Drew got a grade of 'F' on the exam.
Elsa got a grade of 'C' on the exam.
Fred got a grade of 'D' on the exam.

Example: Determining if Elements of a List are Odd or Even

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 [5]:
print(27 % 3 == 0)
print(17 % 3 == 0)
True
False

One common use of the modulus operator is to check if a number is odd or even.

In [6]:
print(19 % 2 == 0 )
print(16 % 2 == 0 )
False
True

A list of integers is provided below. The for loop shown will loop over all of the elements of this list, displaying one of the following messages for each element of the list:

[x] is even.
[x] is odd.
In [7]:
my_list = [74, -55, -77, 58, 0, 91, 62, 0, -91, 61]

for i in range(0, len(my_list)):
    if my_list[i] % 2 == 0:
        print(str(my_list[i]) + " is even.")
    else:
        print(str(my_list[i]) + " is odd.")
74 is even.
-55 is odd.
-77 is odd.
58 is even.
0 is even.
91 is odd.
62 is even.
0 is even.
-91 is odd.
61 is odd.

Example: Determining if Elements of a List are Positive, Negative, or Neither

The cell below contains a look that will print out one of the following messages for each item in my_list.

[x] is positive.
[x] is negative.
[x] is neither positive nor negative.
In [8]:
for i in range(0, len(my_list)):
    
    if my_list[i] < 0:
        print(str(my_list[i]) + " is negative.")
    elif my_list[i] > 0:
        print(str(my_list[i]) + " is positive.")
    else:
        print(str(my_list[i]) + " is neither positive nor negative.")
74 is positive.
-55 is negative.
-77 is negative.
58 is positive.
0 is neither positive nor negative.
91 is positive.
62 is positive.
0 is neither positive nor negative.
-91 is negative.
61 is positive.

Example: Classifying Credit Scores

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 - 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".
In [9]:
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', 'Fred']
credit = [683, 580, 752, 607, 615, 703]

The cell below contains a loop that prints a statement of the following form for each individuals:

[name] has a [bad/poor/fair/good/excellent] credit score. 
In [10]:
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.")
Anna has a fair credit score.
Beth has a bad credit score.
Chad has a excellent credit score.
Drew has a poor credit score.
Elsa has a poor credit score.
Fred has a good credit score.
In [11]:
credit_group = []

for i in range(0, len(names)):
    
    if credit[i] >= 750:
        credit_group.append(4)
    elif credit[i] >= 700:
        credit_group.append(3)
    elif credit[i] >= 650:
        credit_group.append(2)
    elif credit[i] >= 600:
        credit_group.append(1)
    else:
        credit_group.append(0)
        
print(credit)
print(credit_group)
[683, 580, 752, 607, 615, 703]
[2, 0, 4, 1, 1, 3]

Example: Exam Results

In the cell below, we are provided with three lists. The list names contains the names of students, grades1 contains scores for Exam 1, and grades2 contains scores for Exam 2.

In [12]:
names = ['Anna', 'Beth', 'Chad', 'Drew', 'Elsa', 'Fred']
grades1 = [56, 92, 87, 43, 75, 62]
grades2 = [81, 95, 72, 21, 58, 64]

Assume that a grade of 60 or higher is a passing grade. The cell below contains a loop that prints one of the following messages for each student:

[name] passed both exams. 
[name] passed exam 1, but not exam 2. 
[name] passed exam 2, but not exam 1. 
[name] failed both exams. 
In [13]:
for i in range(len(names)):
    
    if (grades1[i] >= 60) and (grades2[i] >= 60):
        print(names[i], 'passed both exams.')
        
    elif (grades1[i] >= 60) and (grades2[i] < 60):
        print(names[i], 'passed exam 1, but not exam 2.')
        
    elif (grades1[i] < 60) and (grades2[i] >= 60):
        print(names[i], 'passed exam 2, but not exam 1.')
        
    elif (grades1[i] < 60) and (grades2[i] < 60):
        print(names[i], 'failed both exams.')
Anna passed exam 2, but not exam 1.
Beth passed both exams.
Chad passed both exams.
Drew failed both exams.
Elsa passed exam 1, but not exam 2.
Fred passed both exams.
In [14]:
for i in range(len(names)):
    
    if (grades1[i] >= 60) and (grades2[i] >= 60):
        print(names[i] + ' passed both exams.')
        
    elif grades1[i] >= 60:
        print(names[i] + ' passed exam 1, but not exam 2.')
        
    elif grades2[i] >= 60:
        print(names[i] + ' passed exam 2, but not exam 1.')
        
    else:
        print(names[i] + ' failed both exams.')
        
Anna passed exam 2, but not exam 1.
Beth passed both exams.
Chad passed both exams.
Drew failed both exams.
Elsa passed exam 1, but not exam 2.
Fred passed both exams.

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. Conditional statements can help us to avoid situations that would result in errors, thus breaking our code.

As an example, assume that we are given a list of item that we know contains a mix of strings, integers, and floats. We want to sum together all of the numerical elements of the list. If we simply pass the list to the sum function, we will get an error. However, we can calculate the desired sum by writing a loop that checks whether or not each element is an string before adding it to the running total. This is illustrated in the code below.

In [15]:
listA = [5.8, 'blah', 3.7, 8, '4', 1, 7.4, 4, 'foo', 6.2]

total = 0

for item in listA:
    if type(item) != str:
        total += item
        
print(total)
36.1