Branching
Contents
21. Branching#
Author: Tue Nguyen
21.1. Outline#
Overview about branching
ifstatementsmatchstatements
21.2. Overview about branching#
When driving a car you often have to consider your current situations and make decision accordingly
Examples
If the traffic light is red, you stop. If it’s green you go
If it is raining, you drive slowly and carefully
You do the same when programming: making your decisions based on the current state of your program
This is called branching
In Python, you do branching using
ifstatementsFrom Python
3.10, you have another way to do braching usingmatchstatements
21.3. if statements#
You can write an if statement in 4 fashions
ifif elseif elifif elif else
21.3.1. Syntax 1: if#
The template for this syntax is as follows
if condition:
# do something
Here
conditionis often an expression that produces aboolvalue (i.e.,TrueorFalse)If
conditionis not readily in thebooltype, Python will do a conversion toboolimplicitlyIf
conditionisTrue, Python executes the code block insideifOtherwise, Python skip to the next statements after
if
# Init a list of integers
numbers = [1, 2, -3, 0, -2, 7, 11]
numbers
[1, 2, -3, 0, -2, 7, 11]
a) Ex 1: print positive integers only
for n in numbers:
if n > 0:
print(n)
1
2
7
11
What happened?
In each iteration of the
forloop, Python compare the current element with0This comparison produces
Trueifnis positive andFalseifnis NOT positiveIf
nis positive, Python executes the print statement and the element is printed outIf not, Python will skip the print statement and move to the statement after
if(if any)However, in this example, there is no statement after
if, and Python notices that it has not reached the last iterationThus, Python moves to the next iteration and repeat the logic above
b) Ex 2: print odd integers only
for n in numbers:
if n % 2 != 0:
print(n)
1
-3
7
11
c) Ex 3: redo Ex 2 with implicit typecasting
for n in numbers:
if n % 2:
print(n)
1
-3
7
11
What happened?
In Ex 3, in each iteration Python computes
n % 2and comes up with an integer, which is the remainder when dividingnby2However,
ifexpects abool, so Python tries to convert the remainder toboolFor example, in the first iteration
ntakes the value1, thusn % 2gives1bool(1)producesTrueso the condition isTrueand Python executes the code insideif(theprintstatement) and you see1is printed out
In the second iteration
ntakes the value2, thusn % 2gives0bool(0)producesFalseso the conditio isFalse, and Python skips the print statement
In general
When
nis odd,n % 2gives1(equivalent toTrue)When
nis even,n % 2gives0(equivalent toFalse)Thus we can write the condition as just
n % 2instead ofn % 2 != 0
However, I recommend using the style in Ex 2 rather than in Ex 3 because it is more readable
Ex 4: print even numbers only using implicit typecasting
# All we need to do is to negate the condition in Ex 3
for n in numbers:
if not (n % 2):
print(n)
2
0
-2
Ex 5: redo Ex 4 in a more readable way
for n in numbers:
if n % 2 == 0:
print(n)
2
0
-2
21.3.2. Syntax 2: if else#
The template for this syntax is as follows
if condition:
# do A
else:
# do B
Here
If
conditionisTrue, Python executes the code block insideifOtherwise, Python executes the code block inside
else
a) Ex 1: print if a person can buy alcohol Suppose that only those who is 18 or older can buy alcohol
# Case 1: can buy
age = 20
if age >= 18:
print("Congrats! You can buy alcohol")
else:
print("Sorry! You cannot buy alcohol")
Congrats! You can buy alcohol
# Case 2: cannot buy
age = 10
if age >= 18:
print("Congrats! You can buy alcohol")
else:
print("Sorry! You cannot buy alcohol")
Sorry! You cannot buy alcohol
a) Ex 2: count numbers of odd and even integers
# Init a list of integers
numbers = [1, 2, -3, 0, -2, 7, 11]
numbers
# Init a counter for each type of integers
# One for odd and the other for event
num_odd = 0
num_even = 0
# Iterate through numbers
# If the element is even, increase num_even by 1
# Otherwise, increase num_odd by 1
for n in numbers:
if n % 2 == 0:
num_even += 1
else:
num_odd += 1
# Print out the results
print(f"{num_even} even integers")
print(f"{num_odd} odd integers")
3 even integers
4 odd integers
21.3.3. Syntax 3: if elif#
The template for this syntax is as follows
if condition_1:
# do A
elif condition_2:
# do B
Here
If
condition_1isTrue, Python executesdo AOtherwise, Python proceeds to check
condition_2in theelifpartIf
condition_2is true, Python executesdo BOtherwise, Python move to the next statement after this
if elifblock
Notes
elifis short forelse ifIf
condition_2is evalued only whencondition_1isFalse
Ex 1) single elif
Check the weather and make decision as follows
If it is sunny, go to the beach
If it is NOT sunny, then check if it is cloudy
If yes, go to the park
Otherwise, do nothing
# Case 1: sunny
weather = "sunny"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
Go to the beach
# Case 2: cloudy
weather = "cloudy"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
Go to the park
# Case 3: raining
# You will see nothing printed out
weather = "raining"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
b) Ex 2: multiple elif
Sometimes you might want to check a series of conditions
If the previous condition is false, we check the next one and so on
Consider the following example: given the month, print the quarter its belongs to
# Case 1: quarter 1
month = 2
if month in (1, 2, 3):
print("Quarter 1")
elif month in (4, 5, 6):
print("Quarter 2")
elif month in (7, 8, 9):
print("Quater 3")
elif month in (10, 11, 12):
print("Quarter 3")
Quarter 1
# Case 2: quarter 4
month = 11
if month in (1, 2, 3):
print("Quarter 1")
elif month in (4, 5, 6):
print("Quarter 2")
elif month in (7, 8, 9):
print("Quater 3")
elif month in (10, 11, 12):
print("Quarter 4")
Quarter 4
21.3.4. Syntax 4: if elif else#
The template for this syntax is as follows
if condition_1:
# do A
elif condition_2:
# do B
else:
# do C
Here
If
condition_1isTrue, Python executesdo AOtherwise, Python proceeds to check
condition_2in theelifpartIf
condition_2is true, Python executesdo BOtherwise, Python executes
do C
The
elsepart is called a catch-all, and it is the default decision when all the checking conditions fail
Ex: redo the weather example above
Suppose that we go to the beach when sunny, go to the park when cloudy, and stay at home in other cases
# Case 1: sunny
weather = "sunny"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
else:
print("Stay at home")
Go to the beach
# Case 2: cloudy
weather = "cloudy"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
else:
print("Stay at home")
Go to the park
# Case 3: raining
weather = "raining"
if weather == "sunny":
print("Go to the beach")
elif weather == "cloudy":
print("Go to the park")
else:
print("Stay at home")
Stay at home
21.3.5. Nested if statements#
You can write an
ifstatement inside anotherifstatementWe call it a nested
ifstatment
Ex 1: check validity of grade and print passing status
Suppose we want to write a program that does the following
Check if a grade is valid (between
0and10)If valid
Print
"Passed"ifgrade >= 4Otherwise, print
"Failed"
If not valid, print out
"Invalid grade"
# Case 1: Passed
grade = 7
if (grade >= 0) and (grade <= 10):
if grade >= 4:
print("Passed")
else:
print("Failed")
else:
print("Invalid grade")
Passed
# Case 2: Failed
grade = 3
if (grade >= 0) and (grade <= 10):
if grade >= 4:
print("Passed")
else:
print("Failed")
else:
print("Invalid grade")
Failed
# Case 3: Invalid grade
grade = 15
if (grade >= 0) and (grade <= 10):
if grade >= 4:
print("Passed")
else:
print("Failed")
else:
print("Invalid grade")
Invalid grade
b) Ex 2: redo Ex 1 using a flat if
Usually (not always) we don’t want nested structures because they reduce readability
We can avoid nested
ifstatements usingif elif elseas follows
# Case 1: Passed
grade = 7
if (grade >= 0) and (grade < 4):
print("Failed")
elif grade <= 10:
print("Passed")
else:
print("Invalid grade")
Passed
# Case 1: Failed
grade = 3
if (grade >= 0) and (grade < 4):
print("Failed")
elif grade <= 10:
print("Passed")
else:
print("Invalid grade")
Failed
# Case 1: Invalid grade
grade = 15
if (grade >= 0) and (grade < 4):
print("Failed")
elif grade <= 10:
print("Passed")
else:
print("Invalid grade")
Invalid grade
21.4. match statement#
Will be updated when Anaconda upgrades to Python 3.10
21.5. Summary#
Branching
Making a decision based on evaluating a condition
In Python, we do branching with
ifstatementsFrom Python
3.10+, we can do branching withmatchstatement
if statements
There are 4 styles to write an
ifstatementifif elseif elifif elif else
The
ifpart is required, but other parts (elif,else) are optionalThe
conditionis normally aboolexpressionIf
conditionis not abool, Python will do an implicit conversion toboolWe can write nested
ifstatements but try to avoid nested structures if possible
match statements
To be updated
21.6. Practice#
To be updated