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
grade = 34
if grade >= 60:
print('You passed the exam.')
print('Congratulations!')
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
grade = 34
if grade >= 60:
print("You passed the exam.")
print("Congratulations!")
else:
print("You failed the exam.")
print("Better luck next time.")
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.
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.")
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.
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.")
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:
print(27 % 3 == 0)
print(17 % 3 == 0)
One common use of the modulus operator is to check if a number is odd or even.
print(19 % 2 == 0 )
print(16 % 2 == 0 )
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.
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.")
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.
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.")
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:
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.
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.")
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)
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.
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.
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.')
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.')
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.
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)