if, elif, else, and match: teaching Python to choose
Introduction to Data Science and Machine Learning · Md Mahbub E Noor · University of Barishal
if marks >= 50:
print("Pass")
else:
print("Try again")Every decision starts with a question. Python answers with True or False (a bool).
| You type | Python gives | Meaning |
|---|---|---|
7 == 7 | True | equal to (two = signs) |
7 != 5 | True | not equal to |
3 > 8 | False | greater than |
3 < 8 | True | less than |
5 >= 5 | True | greater than or equal to |
4 <= 2 | False | less than or equal to |
"free" == "Free" | False | text comparison is case-sensitive |
x = 5 print(x == 5) x = 10 print(x == 5)
What will this print? Write your prediction as a comment before you run the cell.
x = 5 print(x == 5) x = 10 print(x == 5)
True False
x = 10 stores a new value in xx == 5 only asks a question; it changes nothing= and == is the most common beginner bugmarks = 72
if marks >= 50:
print("You passed!")
print("Result checked")
You passed! Result checked
if starts a decision35 >= 50 is False, so the indented line is skippedif does not need an elsemarks = 35
if marks >= 50:
print("You passed!")
print("Result checked")Result checked
marks = 35
if marks >= 50:
print("Pass")
else:
print("Try again")Try again
marks >= 50print("Pass")print("Try again")score = 72
if score >= 80:
print("A")
elif score >= 65:
print("B")
elif score >= 50:
print("C")
else:
print("F")B
score >= 80print("A")score >= 65print("B")score >= 50print("C")print("F")Python checks from the top and stops at the first True. Later conditions are not even checked.
if score >= 80:
print("A")
elif score >= 65:
print("B")
elif score >= 50:
print("C")
else:
print("F")| score | >= 80 | >= 65 | >= 50 | prints |
|---|---|---|---|---|
| 95 | True | not checked | not checked | A |
| 72 | False | True | not checked | B |
| 55 | False | False | True | C |
| 20 | False | False | False | F |
Next row: arrow key or the ▶ button. Predict it first!
WATCH FOR
Silent video: press play, pause any time.
score = 92
if score >= 50:
print("C")
elif score >= 65:
print("B")
elif score >= 80:
print("A")What will this print? Write your prediction as a comment before you run the cell.
score = 92
if score >= 50:
print("C")
elif score >= 65:
print("B")
elif score >= 80:
print("A")C
92 >= 50 is True, so Python stops at the first branchand needs both. or needs at least one. not flips True and False.
| You type | Python gives | Meaning |
|---|---|---|
True and True | True | both True, so True |
True and False | False | one False is enough to make and False |
False or True | True | one True is enough to make or True |
False or False | False | nothing True, so False |
not True | False | not flips the value |
5 > 3 and "a" in "cat" | True | real conditions combine the same way |
andand is a full conditionage >= 18 and age <= 60, not age >= 18 and <= 60age = 20
has_id = True
if age >= 18 and has_id:
print("Can enter")
else:
print("Cannot enter")Can enter
and keeps the code flattermarks = 72
attendance = 60
if marks >= 50:
if attendance >= 75:
print("Pass")
else:
print("Pass marks, low attendance")
else:
print("Fail")Pass marks, low attendance
in checks whether text appears inside other text.lower() first, so FREE and free both matchor: any one suspicious word is enoughmessage = "Claim your FREE prize"
text = message.lower()
if "free" in text or "prize" in text:
print("Suspicious")
else:
print("Looks normal")Suspicious
match compares one value with several patterns| means or inside a casecase _: catches everything else, like elsenumber[:3] = first 3 characters (Lecture 3.2)number = "01711111111"
match number[:3]:
case "017" | "013":
print("Grameenphone")
case "019" | "014":
print("Banglalink")
case "018":
print("Robi")
case _:
print("Unknown operator")Grameenphone
Read the last line of an error first. It names the problem.
| What you typed | What Python says | What it means |
|---|---|---|
if marks >= 50
print("ok") | SyntaxError: expected ':' | Missing colon at the end of the if line. |
if marks = 50:
print("ok") | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? | One = stores. To compare, use ==. |
if marks >= 50:
print("ok") | IndentationError: expected an indented block after 'if' statement on line 1 | The block must be indented under the if. |
if "5" > 3:
print("ok") | TypeError: '>' not supported between instances of 'str' and 'int' | Text and numbers cannot be compared. Convert with int("5"). |
Work in pairs. 15 minutes. n % 2 is the remainder after dividing n by 2.
Given n, print Even or Odd. Test: 7 gives Odd, 10 gives Even.
Given a, b, c, print the largest using if/elif/else, without max(). Test: 4, 9, 2 gives 9.
Leap if divisible by 4 and not by 100, or divisible by 400. Test: 2024 Leap, 1900 Not leap, 2000 Leap.
Extend the match example with Teletalk (015) and Airtel (016). Print INV if the number is not exactly 11 characters.
Show these after students have tried the exercises.
Test every branch: try values that should give each possible answer.
n = 7
if n % 2 == 0:
print("Even")
else:
print("Odd")
a = 4
b = 9
c = 2
if a >= b and a >= c:
print(a)
elif b >= c:
print(b)
else:
print(c)Odd 9
The brackets group the first two conditions. Test the tricky years: 1900 and 2000.
year = 1900
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("Leap")
else:
print("Not leap")Not leap
The else matters: without it, a wrong-length number would print INV and then also an operator name.
number = "0151234567"
if len(number) != 11:
print("INV")
else:
match number[:3]:
case "017" | "013":
print("Grameenphone")
case "019" | "014":
print("Banglalink")
case "015":
print("Teletalk")
case "016":
print("Airtel")
case "018":
print("Robi")
case _:
print("INV")INV
In the lab you can
Opens in a new tab and works offline. All labs: labs/START_HERE.html
== != > < >= <= | Compare, gives True/False |
if condition: | Run the block only if True |
else: | Run when nothing above was True |
elif condition: | Another check, only if earlier failed |
and / or / not | Combine or flip conditions |
"x" in text | Does text contain x? |
match value: | Compare one value with many options |
case "a" | "b": | Matches a or b |
case _: | Anything else |
Due before Lecture 3.2 · [date]
Write predictions as comments first: print(10 != 10), print(not (3 > 5)), print("a" in "Data" and 2 < 1).
Store a temperature. Print Cold (below 15), Pleasant (15 to 27) or Hot (above 27). Test 14, 15, 27, 28.
Price is 50 for age under 12 or students, 100 otherwise. Store age and is_student and print the price.
Store a message. Print High if it contains both "win" and "cash", Medium if either, otherwise Low. Ignore capitals.
The "Does the order matter" slide prints C for 92. Fix the code and explain the bug in one sentence.
Watch it again at home to revise.