Python - conditional execution

Python conditional execution

Conditional execution

Simple If - else block:

In [1]:
a = 20

if a < 10:
    print("A less than 10")
else:
    print("A greater than or equal to 10")
A greater than or equal to 10

Implementing a switch block using elif

In [5]:
a = 13

if a < 5:
    print("a is less than 5")
elif a < 10:
    print("a is greater than 5 but less than 10")
elif a < 15:
    print("a is greater than 10 but less than 15")
else:
    print("a is greater than 15")
a is greater than 10 but less than 15

Between check

In [6]:
a = 16

if 5 < a < 25:
    print("A is between 5 and 25")
A is between 5 and 25

Ternary operator

In [8]:
a=5
'a less than 5' if a < 5 else 'a greater than or equal 5'
Out[8]:
'a greater than or equal 5'

Truthy checks

How do the following evaluate on a truthy check?

In [11]:
my_list = [0, 1, -1, 5, True, False, [], 'a', '', ' ', {'a':'vak'}, {}]

for e in my_list:
    print(f'{e}: , True') if e else print(f'{e}: False')
0: False
1: , True
-1: , True
5: , True
True: , True
False: False
[]: False
a: , True
: False
 : , True
{'a': 'vak'}: , True
{}: False

We see that 0, False, empty string, empty list, empty dict eval to False. While 1, -1, string with space or any char all eval to True.

In [ ]: