Conditions

A condition is True or False. Some examples:

4 > 3  # Is 4 bigger than 3?
True
4 < 3  # Is 4 smaller than 3?
False
4 == 3  # Is 4 equal to 3?
False
4 == 4  # Is 4 equal to 4?
True
4 != 4 # Is 4 not equal to 4?
False

The data type is called Boolean:

type(4==3)
bool
type(False)
bool
type(True)
bool

Multiple conditions

It’s possible to combine multiple conditions with the keywords and and or:

10 > 5 and 5 > 4
True
-124 > 0 or 1e-4 > 0
True
True or False
True
True and False
False
'hell' in 'hello'
True
'heaven' in 'hello'
False

in

With the keyword in we can evaluate if an item is included in a list or a string.

'app' in 'apple'
True
food = ['apple', 'berry', 'date', 'eel', 'firebird', 'mango']
'apple' in food
True
'catfish' not in food
True

If we want to check multiple conditions, we have to separate them:

# Does not work as expected:
'catfish' and 'firebird' in food
True
'catfish' in food and 'firebird' in food
False
'catfish' in food or 'firebird' in food
True

With is we can ask for the identity of an object.

s = 'text'
type(s) is str
True

if elif else (Decision Making)

With if, elif (optional) and else you can specify to execute a block of code based on the boolean (True and False) of a condition.

if True:
    print('code block is executed')
    print('still inside')
else:
    print('this is not executed')
    
print('executed in any case')
code block is executed
still inside
executed in any case

The syntax is similar to writing a for-loop. The statement is finished with a :, followed by lines of code with indent. The first line without indent marks the end of the block of code.

It’s also possible to create a variable of type boolean:

i_like_coffee = True
if i_like_coffee:
    print('☕')
else:
    print('🫖')

We can use if elif else if we want to evaluate multiple conditions.

a, b = 4, 8
if a > b:
    print(a, '>', b)
elif a < b:
    print(a, '<', b)
else:
    print(a, '=', b)
4 < 8

Conditions are used to control the program flow: If some condition is True, do that, else (if it is False) do that.

a = -7
if a > 0:
    a = a*2
else:
    a = a*-2
    
print(a)
14

list comprehension with conditions

food = ['apple', 'berry', 'date', 'eel', 'firebird', 'mango']

# Add all items to the new list if their length is smaller than or equal 4.
short_names = [item for item in food if len(item) <= 4]

print(short_names)
['date', 'eel']
l = [24, 10, 4, 14, 6.24 , 1, .5, 100]

# reduce list to int between 0 and 10
l = [n for n in l if type(n) is int and n >= 0 and n <= 10]
print(l)
[10, 4, 1]
# Another (more readable) solution
l = [24, 10, 4, 14, 6.24 , 1, .5, 100]
print(l)
query = [x for x in range(11)]
print(query)
l = [n for n in l if n in query]
print(l)
[24, 10, 4, 14, 6.24, 1, 0.5, 100]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[10, 4, 1]