11  Logic and Flow

11.1 Bool

A Boolean expression is one that evaluates to either True or False.

5 < 7
True

Given two values a and b, the following are Boolean comparisons:

Description Operator Python
Less than \(<\) a < b
Less than or equal \(\leq\) a <= b
Greater than \(>\) a > b
Greater than or equal \(\geq\) a >= b
Equal to \(=\) a == b

That last one can be easy to mix up with assignment.

11.2 If

if CONDITION:
    BODY OF CODE

11.3 Else

Sometimes we want to do one thing if a condition is true, else we want to do something else if it wasn’t true.

num = np.random.rand() 

if num < 0.5:
    print('HEADS')
else: 
    print('TAILS')

11.4 Else If

11.5 Using logic to slice arrays

import numpy as np 

arr = np.array([[1, 2],[3, 4],[5 ,6]])
arr[:,1] > 2
array([False,  True,  True])

11.6 Exercises