5. Control Flow: Conditional statements#
Read WTOP Ch 7.
Control flow refer to commands that determine which code runs and how many times. The main tools of control flow are:
Conditional Statements - statements that allow you to run different code under certain conditions
Loops - statements that allow you to run blocks of code multiple times
5.1. Conditional Statements#
Conditional statements determine if code will run using if, elif (abbreviation of else if), and else statements.
5.1.1. If statements#
Run some code if a condition is met.
If it’s nice outside, I’m going to play tennis.
If I’m not sleepy, I’ll watch the fourth quarter.
If the requested withdrawal amount is more than the amount in your checking account, the transaction will be declined.
5.1.2. If-else statements#
This gives one path of code if the condition is met and another path for all other cases.
If it’s nice outside, I’m going to play tennis. Else (otherwise), I’ll go the gym to play basketball.
If I’m not sleepy, I’ll watch the fourth quarter, else I’ll go to bed.
If the requested withdrawal amount is more than the amount in your checking account, the transaction will be declined, else the funds will be transferred to the vendor.
5.1.3. if-elif-else#
This gives a sequence of conditions, if one isn’t met then you move onto the next option. if-elif may or may not have an else statement at the end (mostly they do).
If it’s nice outside I’m going to play tennis, else if it’s just drizzling I’ll go to the gym to play basketball, else I’ll stay home and watch a show.
If I’m not sleepy, I’ll watch the fourth quarter of the game. Else if I’m a little sleepy, I’ll watch the first five minutes then go to bed. Else, I’ll go to bed right away.
If the requested withdrawal amount is more than the amount in your checking account, the transaction will be declined, else if you have the funds but the remaining balance is less than $50, the funds will be transferred to the vendor and the buyer will get a “low balance” notification. Else, the funds will be transferred to the vendor.
The if-elif-else statements don’t have to be particularly related:
If it’s nice outside, I’ll play tennis. Else if I’m feeling hungry, I’ll eat a bowl of cereal. Else if the dollar is strong, my dad will invest in foreign currency. Else, print “they’re all good dogs”.
5.1.3.1. Syntax for if-elif-else#
if <condition 1>:
<code block 1>
elif <condition 2>:
<code block 2>
elif <condition 3>:
<code block 3>
.
.
.
else:
<code block 0>
5.1.3.2. Example Problem 1#
Let’s write a set of if statements that check if a student is keeping up with their work. If a student is earning above an 80, they are in good standing and nothing needs to be done. If they are earning between 60-80, they’re struggling and should get a note to attend office hours. If they are below 60, they are failing and should get a notification to schedule a one-on-one with the professor.
# inequality
# indentation
# return vs print
def studentAdvisory(grade):
if 60 <= grade < 80:
return 'Attend office hours.'
elif grade >= 80:
return
else:
return 'Schedule 1-on-1 with Professor'
def studentAdvisory(grade):
if grade < 60:
return 'Schedule 1-on-1 with Professor.'
elif grade < 80:
return 'Attend office hours.'
num = 10
9 < num < 11
True
print(studentAdvisory(80))
None
5.1.3.3. Example Problem 2#
Write a function using conditional statements (if-elif-else) that returns whether or not a year is a leap year.
Rules for leap years: divisible by 400 or divisible by 4 and not divisible by 100
New Operator! % (mod/modulo)
5 % 4 == 1
100 % 7 == 2
8 % 20 == 8
Five divided by 4 leaves 1 as the remainder. If the result of a modulo operation is 0, the numerator is divisible by the denominator. For example:
21 % 3 == 0
100 % 25 == 0
57 % 57 == 0
Rules for leap years: divisible by 400 or divisible by 4 and not divisible by 100
def isLeapYear(year):
if year % 4 == 0 and year % 100 != 0:
elif year % 400 == 0:
return True
else:
return False
def isLeapYear(year):
return (year % 400 == 0) or (year % 4 == 0 and year % 100 !=0)
Cell In[4], line 3
elif year % 400 == 0:
^
IndentationError: expected an indented block after 'if' statement on line 2
print(isLeapYear(1600)) # True
print(isLeapYear(1900)) # False
print(isLeapYear(2000)) # True
print(isLeapYear(2001)) # False
print(isLeapYear(2004)) # True
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[5], line 1
----> 1 print(isLeapYear(1600)) # True
2 print(isLeapYear(1900)) # False
3 print(isLeapYear(2000)) # True
NameError: name 'isLeapYear' is not defined
What would the difference be between:
refrigerator = ['apple', 'grapes', 'turkey sandwich', 'banana', 'eggs', 'milk', 'water']
Case 1: if-elif-else
if have(apple):
eat(apple)
elif have(banana):
eat(banana)
else:
eat(water)
Case 2: if-if-else
if have(apple):
eat(apple)
if have(banana):
eat(banana)
else:
eat(water)
Case 3: if-elif-elif
if have(apple):
eat(apple)
elif have(banana):
eat(banana)
elif have(water):
eat(water)
New List Functions! ‘in’ and .pop()
in is used as a boolean operation to check if a list contains a specified item
list.pop() removes items from a list and return that item. It also updates the list in place. If no input argument is provided, pop removes the last element of the list. If an integer is provided, pop removes the item at that position in the list.
Let’s demo these new tools!
passengers = ['Alican', 'Tanvi', 'Saber', 'Vinutha', 'Jusuk', 'Eatai', 'Ramona']
deboarded_passenger = passengers.pop(3)
print(deboarded_passenger)
print(passengers)
Vinutha
['Alican', 'Tanvi', 'Saber', 'Jusuk', 'Eatai', 'Ramona']
5.1.3.4. Example Problem 3#
Let’s write this as a function, eat_fruit that takes as an input a list of things we have available to eat. If the item we want to eat is on the list, we should remove it from the list. The function should return an updated list with the foods we have eaten removed. If a food is not in the refrigerator, still return the list unchange but also print ‘That item is unavailable’.
def eat_fruit(fridge, fruit):
if fruit in fridge:
idx = fridge.index(fruit)
fridge.pop(idx)
else:
print('That item is unavailable')
return fridge
refrigerator = ['apple', 'grapes', 'turkey sandwich', 'banana', 'eggs', 'milk', 'water']
print(refrigerator)
print(eat_fruit(refrigerator, 'apple'))
print(eat_fruit(refrigerator, 'raspberry'))
print(eat_fruit(refrigerator, 'grapes'))
print(eat_fruit(refrigerator, 'grapes'))
['apple', 'grapes', 'turkey sandwich', 'banana', 'eggs', 'milk', 'water']
['grapes', 'turkey sandwich', 'banana', 'eggs', 'milk', 'water']
That item is unavailable
['grapes', 'turkey sandwich', 'banana', 'eggs', 'milk', 'water']
['turkey sandwich', 'banana', 'eggs', 'milk', 'water']
That item is unavailable
['turkey sandwich', 'banana', 'eggs', 'milk', 'water']
5.1.4. Match-Case#
Match-case (switch-case in basically every other programming language) is another way of achieving the selectivity of if statements. Match-case statements use one variable as a selector and enumerate the different cases.
5.1.5. Syntax for match-case#
match <match variable>:
case <case 1>:
<codeblock 1>
case <case 2>:
<codeblock 2>:
.
.
.
case other: # alternatively case _
<codeblock 0>
Note: For those that are familiar with switch-case from another language, Python’s match-case does NOT fall through: one match and done.
5.1.6. Example Problem 4#
Below, I’ve written a function that checks if a letter is a vowel or not.
def isAVowel(char):
lowchar=char.lower()
match lowchar:
case 'a'|'e'|'i'|'o'|'u': # | (pipe) lumps different cases with same outcome. | means 'OR'
print(f'yes, "{char}" is a vowel.')
return True
case 'y':
print(f'"{char}" can sometimes act as a vowel.')
return False
case 'b'|'c'|'d'|'f'|'g'|'h'|'j'|'k'|'l'|'m'|'n'|'p'|'q'|'r'|'s'|'t'|'v'|'w'|'x'|'y'|'z':
print(f'no! "{char}" is not a vowel.')
return False
case _:
print('You must enter a single alphabetic character.')
return False
isAVowel('aeiou')
You must enter a single alphabetic character.
False
5.1.7. Example Problem 5#
Let’s revisit PS1 and write a daysInMonth function using match-case. The function should take as input the name of a month as a string and return the number of days in the month.
def daysInMonth(month):
Cell In[11], line 2
^
_IncompleteInputError: incomplete input
5.1.7.1. Example Problem 6#
Write a match-case block that gives different heat advisories depending on the temperature. The advisory levels should be as follows:
higher than 105 - level 5
100-105 - level 4
95-100 - level 3
80-95 - level 2
less than 80 - level 1
Also have the block print some cautionary message for each level.
When the condition you want to check is a more complicated condition on the match parameter, you have to use a special format for the case statement.
case x if (condition on x):
You might as well just use if statements in this case.
def weatherAdvisory(temp):
match temp:
case temp if temp>105:
advisory_level = 5
print('Dangerously Hot! Stay indoors.')
case temp if temp>100:
advisory_level = 4
print('Dangerously hot! Be outdoors for short periods only if necessary.')
case temp if temp>95:
advisory_level = 3
print('Wear sunscreen.')
case _:
print('It\'s fine.')
advisory_level = 0
return advisory_level
def weatherAdvisory(temp):
if temp>105:
advisory_level = 5
print('Dangerously Hot! Stay indoors.')
elif temp>100:
advisory_level = 4
print('Dangerously hot! Be outdoors for short periods only if necessary.')
elif temp>95:
advisory_level = 3
print('Wear sunscreen.')
else:
print('It\'s fine.')
advisory_level = 0
return advisory_level
weatherAdvisory(96)
Wear sunscreen.
3
5.1.8. QUIZ YOURSELF#
In the cells below, I’ve written some code. Try to predict what this code does. Check if you’ve understood by running the code or testing the functions.
5.1.8.1. Q1#
a = range(1,100) # creates a list with numbers 1-99
group0 = a[0::5]
group1 = a[1::5]
group2 = a[2::5]
group3 = a[3::5]
group4 = a[4::5]
What did that do?
5.1.8.2. Q2#
petLegs = {
'cat':4,
'dog':4,
'rodent':4,
'bird':2,
'tarantula':8,
'hissing cockroach':6,
'fish':0,
'snake':0,
'toddler':2
}
def comparePets(animal1, animal2):
if petLegs[animal1] > petLegs[animal2]:
print(f'A {animal1} has {petLegs[animal1]-petLegs[animal2]} more legs than a {animal2}.')
elif petLegs[animal1]==petLegs[animal2]:
print(f'A {animal1} and a {animal2} have the same number of legs, {petLegs[animal1]}.')
else:
print(f'A {animal1} has {petLegs[animal2]-petLegs[animal1]} fewer legs than a {animal2}.')
What did that do?
5.1.8.3. Q3#
def huh(x,y):
return x==y
def heh(p=0,n=0,d=0,q=0):
t = 0.01 * p + 0.05*n + 0.1*d + 0.25*q
return t