21. Branching#

Author: Tue Nguyen

21.1. Outline#

  • Overview about branching

  • if statements

  • match statements

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 if statements

  • From Python 3.10, you have another way to do braching using match statements

21.3. if statements#

You can write an if statement in 4 fashions

  • if

  • if else

  • if elif

  • if elif else

21.3.1. Syntax 1: if#

The template for this syntax is as follows

if condition:
    # do something

Here

  • condition is often an expression that produces a bool value (i.e., True or False)

  • If condition is not readily in the bool type, Python will do a conversion to bool implicitly

  • If condition is True, Python executes the code block inside if

  • Otherwise, 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 for loop, Python compare the current element with 0

  • This comparison produces True if n is positive and False if n is NOT positive

  • If n is positive, Python executes the print statement and the element is printed out

  • If 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 iteration

  • Thus, 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 % 2 and comes up with an integer, which is the remainder when dividing n by 2

  • However, if expects a bool, so Python tries to convert the remainder to bool

  • For example, in the first iteration

    • n takes the value 1, thus n % 2 gives 1

    • bool(1) produces True so the condition is True and Python executes the code inside if (the print statement) and you see 1 is printed out

  • In the second iteration

    • n takes the value 2, thus n % 2 gives 0

    • bool(0) produces False so the conditio is False, and Python skips the print statement

  • In general

    • When n is odd, n % 2 gives 1 (equivalent to True)

    • When n is even, n % 2 gives 0 (equivalent to False)

    • Thus we can write the condition as just n % 2 instead of n % 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 condition is True, Python executes the code block inside if

  • Otherwise, 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_1 is True, Python executes do A

  • Otherwise, Python proceeds to check condition_2 in the elif part

    • If condition_2 is true, Python executes do B

    • Otherwise, Python move to the next statement after this if elif block

  • Notes

    • elif is short for else if

    • If condition_2 is evalued only when condition_1 is False

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_1 is True, Python executes do A

  • Otherwise, Python proceeds to check condition_2 in the elif part

    • If condition_2 is true, Python executes do B

    • Otherwise, Python executes do C

  • The else part 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 if statement inside another if statement

  • We call it a nested if statment

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 0 and 10)

  • If valid

    • Print "Passed" if grade >= 4

    • Otherwise, 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 if statements using if elif else as 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 if statements

  • From Python 3.10+, we can do branching with match statement

if statements

  • There are 4 styles to write an if statement

    • if

    • if else

    • if elif

    • if elif else

  • The if part is required, but other parts (elif, else) are optional

  • The condition is normally a bool expression

  • If condition is not a bool, Python will do an implicit conversion to bool

  • We can write nested if statements but try to avoid nested structures if possible

match statements

  • To be updated

21.6. Practice#

To be updated