Lecture 05 - Conditional Statements
Today we will:
if
, elif
, and else
statementsif
statementsLet’s get started! 🚀
if
statement is used to execute a block of code if a condition is True
elif
statement is used to execute a block of code if the first condition is False
and the second condition is True
else
statement is used to execute a block of code if all other conditions are False
else
statement is used to execute a block of code if the condition is False
else
statement is always used in conjunction with the if
statementelse
statement syntax is as follows:# Here we want to change the colour of the histogram
# based on a conditional statement
import numpy as np
import matplotlib.pyplot as plt
is_graph_red = False
how_many_classes = np.array([7,1,2,3,3,3,4,5,6])
if is_graph_red:
plt.hist(x = how_many_classes, color="red")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
else:
plt.hist(x = how_many_classes, color="purple")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
is_graph_red
is True
, and purple otherwiseWhat happens if … ? Try the following:
is_graph_red
.is_graph_red
?:
if
Appendix 04elif
statementelif
statement is used to execute a block of code if the first condition is False
and the second condition is True
if
statement, but it is used when you have more than two possible outcomeselif
statement syntax is as follows:&
(and)|
(or)~
(not)==
(equal)!=
(not equal)>
(greater than), <
(less than), etcif
statementsif
statement can be placed inside another if
(or elif
/else
) statement. This is called nesting.if condition1:
# Outer if body
print("Condition 1 is True")
if condition2:
# Inner if body
# Executes if condition1 AND condition2 are True
print("Condition 2 is also True")
else:
# Inner else body
# Executes if condition1 is True BUT condition2 is False
print("Condition 2 is False")
else:
# Outer else body
print("Condition 1 is False")
The path is like a tree: 1. Check condition1
(outer if
). 2. If True
, check condition2
(inner if
). 3. If False
, go to the inner else
. 4. If condition1
is False
, go to the outer else
.
if
example: ticket pricingScenario: Ticket price depends on age group, and then on the day of the week for adults.
age = 30
day = "Saturday" # Try "Monday"
price = 0
if age < 18: # Child
price = 10
category = "Child"
elif age >= 18 and age < 65: # Adult
category = "Adult"
if day == "Saturday" or day == "Sunday":
price = 20 # Weekend adult price
else:
price = 15 # Weekday adult price
else: # Senior
price = 12
category = "Senior"
print(f"Category: {category}, Day: {day}, Price: ${price}")
Category: Adult, Day: Saturday, Price: $20
Modify the ticket pricing example:
age
is between 18 and 25 (inclusive) AND an assumed variable is_student = True
, their price is always $13. This should take precedence over the standard adult pricing.if/else
statements that assign a value to a variable or return a value. This is known as a conditional expression or a “ternary operator”.value_if_true if condition else value_if_false
condition
:
True
, the whole expression evaluates to value_if_true
.False
, the whole expression evaluates to value_if_false
.Standard if/else
for assignment:
age = 20
status = ""
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(f"Status (standard if/else): {status}")
Status (standard if/else): Adult
Using Conditional Expression:
Another Example (Setting a discount):
is_member = True
# is_member = False # Try this
base_price = 100
discount_rate = 0.10 if is_member else 0.0
final_price = base_price * (1 - discount_rate)
print(f"Is member: {is_member}")
print(f"Discount rate: {discount_rate*100}%")
print(f"Final price: ${final_price}")
Is member: True
Discount rate: 10.0%
Final price: $90.0
elif
Statementsif...elif...else
chain are evaluated in order from top to bottomTrue
will have its block of code executed, and the rest of the chain is skippedProblematic Order (Grading):
score = 95
grade = ""
# This is problematic because score >= 60 is true for 95
if score >= 60:
grade = "D"
elif score >= 70:
grade = "C"
elif score >= 80:
grade = "B"
elif score >= 90:
grade = "A" # This will never be reached if score is >= 60
else:
grade = "F"
print(f"Score: {score}, Problematic Grade: {grade}")
Score: 95, Problematic Grade: D
Correct Order (Grading):
None
objectNone
is a special object in Python that represents the absence of a valueNone
is often used to represent missing values or, in our case today, placeholdersNone
is not the same as 0
, False
, or an empty string ''
None
, as it is not a stringNone
:Note
You can read more about None
at https://realpython.com/null-in-python/.
list.append()
methodlist.append()
commandlist.extend()
method*
operatorlist = [value] * n
[7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]
['Nashville', None, None, 'Nashville', None, None, 'Nashville', None, None, 'Nashville', None, None]
np.array
objects when doing operations+
operator[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
# When you multipy an array times a number, you multiply each element
import numpy as np
vec_a = np.array(list_a)
print(vec_a * 4)
[ 4 8 12]
Important
Check that it works by trying different values of “points”!
age = 31
) is strictly less than 20, or greater than 30The second answer uses |
because &
evaluates both statements at the same time, and one cannot be less than 25 and greater than 27 at the same time. Therefore, it must be |
.
What happens if is_graph_red
is set to True
?
is_graph_red = True
how_many_classes = np.array([7,1,2,3,3,3,4,5,6])
if is_graph_red:
plt.hist(x = how_many_classes, color="red")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
else:
plt.hist(x = how_many_classes, color="purple")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
What happens if you set a non-boolean value of is_graph_red
?
It is considered True
if it is not zero
is_graph_red = 39
how_many_classes = np.array([7,1,2,3,3,3,4,5,6])
if is_graph_red:
plt.hist(x = how_many_classes, color="red")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
else:
plt.hist(x = how_many_classes, color="purple")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
What happens if you don’t include :
?
is_graph_red = True
how_many_classes = np.array([7,1,2,3,3,3,4,5,6])
if is_graph_red
plt.hist(x = how_many_classes, color="red")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
else:
plt.hist(x = how_many_classes, color="purple")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
What happens if you don’t indent the body of the if
?
You will get another syntax error
is_graph_red = True
how_many_classes = np.array([7,1,2,3,3,3,4,5,6])
if is_graph_red:
plt.hist(x = how_many_classes, color="red")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
else:
plt.hist(x = how_many_classes, color="purple")
plt.title("Count of students in each category")
plt.xlabel("How many classes are you taking?")
plt.show()
age = 22
is_student = True
day = "Saturday" # Try "Monday"
price = 0
if age < 18: # Child
price = 10
category = "Child"
elif (age >= 18 and age <= 25) and is_student: # Student
price = 13
category = "Student"
elif age >= 18 and age < 65: # Adult
category = "Adult"
if day == "Saturday" or day == "Sunday":
price = 20 #
elif age >= 18 and age < 65: # Adult
category = "Adult"
if day == "Saturday" or day == "Sunday":
price = 20 # Weekend adult price
else:
price = 15 # Weekday adult price
else: # Senior
price = 12
category = "Senior"
print(f"Category: {category}, Day: {day}, Price: ${price}")
Category: Student, Day: Saturday, Price: $13
list_personal = []
list_personal.append("First element")
list_personal.append("Second element")
print(len(list_personal))
2
# Here I used the index -1 to change the last element
# You could also use the index 1
list_personal[-1] = "Last element"
print(list_personal)
['First element', 'Last element']