26. Conditionals#

Conditionals help us to change the flow of the code at the runtime. The three conditional keywords are if, else, elif.

Hereโ€™s again we need to praise the readability ๐Ÿ™‚, if, else, elif are pretty english words, just that elif is the short-hand keyword of else-if.

Letโ€™s start with the if conditionโ€ฆ

26.1. if#

The syntax of if is:

if <expression>:
    # Do stuff here.
    ...

In the earlier chapters, we have learnt about Truth value testing, if absolutely works based on the truth value of the operand.

If the expression results in Truth value equivalent to True, then our interpreter gets into the block of code written in the if block, else it skips the if block.

if 3 > 1:
    print("Yup!, 3 is greater than 1")
Yup!, 3 is greater than 1

One more:

# Just for demonstration, we are doing a bit long way.
tuple_1 = (3, 2, 1)
tuple_2 = (1, 2, 3)

result = tuple_1 > tuple_2
print(f"The result is {result}")
if result:
    print("tuple_1 is greater than tuple_2")

result_2 = tuple_1 < tuple_2
print(f"The result_2 is {result_2}")
if result_2:
    print("๐Ÿ˜ฌ The interpreter doesn't run this code")
The result is True
tuple_1 is greater than tuple_2
The result_2 is False

In the above example, we can see that result value is True which made the if condition satisfy and the print function saying tuple_1 is greater than tuple_2 is executed, but our result_2 value is False, and hence the print function in the second if condition didnโ€™t get executed as we thought ๐Ÿ˜Š.

On a list containing few objects

my_list = [1, 2, None, "abc", "๐Ÿ"]
if my_list:
    print("I am inside of the if block")
I am inside of the if block

We see that the print function is executed as the Truth value of list containing objects is True.

On empty list

empty_list = []
if empty_list:
    print("Nah! I won't get executed")

We see thereโ€™s no output generated in the above example, as Truth value of empty list is False.

Hint

Truth value of an object can be found using bool(<obj>).

26.2. elif#

The elif is a short hand of else-if, if the if condition written above the elif gets Falsy condition, then only the interpreter gets to the elif block. There could be 0 or any number of elif conditions.

if 3 > 4:
    print(
        "3 is greater than 4! ๐Ÿ˜…"
    )  # This wouldn't get executed as 3 is not greater than 4.
elif 4 > 3:
    print("4 is greater than 3! ๐Ÿ˜Š")
4 is greater than 3! ๐Ÿ˜Š

26.3. else#

else condition doesnโ€™t have a condition statement, it works if the above if or elif doesnโ€™t gets executed as the conditional statement in it has falsy values.

if 1 > 2:
    print("1 is greater than 2")  # doesn't gets executed as 1>2 is False.
elif 3 > 4:
    print("3 is greater than 4")  # doesn't gets executed as well as 3>4 is False.
else:
    print("Hey! I am inside else condition!")
Hey! I am inside else condition!

26.4. TLDR about if, else, elif#

Using all the if, else and elif together:

if <condition 1>:
    ...
elif <condition 2>:
    ...
else:
    ...

26.4.1. Points to remember:#

  • There can be any number of if conditions.

  • There can be any number of elif conditions too, just that they should be after the if or elif condition.

We can even write a if else expression in a single statement.

Letโ€™s find if a number is even or odd

value = 4
if value % 2 == 0:
    is_even = True
else:
    is_even = False
print(is_even)
True

The above if-else conditions can be written in a single line using if-else statements as:

value = 4
is_even = True if value % 2 == 0 else False  # single line if-else statement.
print(is_even)
True

26.5. match-case#

Python developers have been asking for the switch case statements since ages which is available in other languages, Alternatively most programmers used dictionary for switch casing:

Current alternate way of simple switch-case in Python:

def int_1():
    print("I am integer one")


def int_2():
    print("I am integer two")


def python():
    print("I am one of the great programming language ๐Ÿ!")


my_dict = {
    1: int_1,
    2: int_2,
    "Python": python,
}

In the above code, we have written 3 functions int_1, int_2 and python, each function has a print statement, which in real world applications can be any code. We created a dictionary called my_dict which has keys as 1, 2, Python and those keys have values as function objects int_1, int_2 and python respectively. Note: We are not calling the functions.

try:
    func = my_dict[1]  # Getting the function object.
    func()  # Executing the function object.
    func = my_dict[2]
    func()
    func = my_dict["Python"]
    func()
    func = my_dict[
        "Random Key"
    ]  # We don't have a key called "Random Key". Hence, it raises KeyError.
except KeyError as exc:
    print(f"Ouch, there is no switch for the value: {exc}")
I am integer one
I am integer two
I am one of the great programming language ๐Ÿ!
Ouch, there is no switch for the value: 'Random Key'

We are trying to get the values in the dictionary using the key provided, so, for the keys 1, 2 and Python we are successfully able to get the function object and able to call the function.

We donโ€™t have a key called Random Key in our my_dict, so, while trying my_dict["Random Key"] we are seeing the KeyError being raised. We can catch the KeyError and this block can have the code equivalent to default case of other languages ๐Ÿ˜Š.

26.5.1. ๐Ÿ’ก#

No worries! Python community has listened to our asks and provided match-case in Python 3.10 ๐Ÿš€