Boolean logic ↩
Logical operators are typically used to evaluate whether two or more expressions are True
or False
.
The ‘and’ operator
The and
operator evaluates if two or more statements are True
. It returns True
only if all expressions are True
; in all other cases it returns False
.
and | True | False |
---|---|---|
True | True | False |
False | False | False |
In the example below, we want to do something only if both values are bigger than 15
, otherwise we’ll do something else:
a = 17 # try different values here
b = 17
if a > 15 and b > 15:
print("do something")
else:
print("do something else")
The ‘or’ operator
The or
operator evaluates if at least one among several statements is True
. It returns False
only if all expressions are False
; in all other cases it returns True
.
or | True | False |
---|---|---|
True | True | True |
False | True | False |
In the example below, we’ll do something if at least one value is bigger than 15
, otherwise we’ll do something else:
a = 17 # try different values here
b = 17
if a > 15 or b > 15:
print("do something")
else:
print("do something else")
The ‘not’ operator
The not
operator simply inverts the value of an expression: if the expression is True
, it returns False
; if the expression is False
, it returns True
.
True | False | |
---|---|---|
not | False | True |
A simple example:
>>> a = 300 > 12
>>> a
True
>>> not a
False
The not
operator is often used in combination with the keyword in
for testing item membership.
In this next example we print out the strings which are in L1
but not in L2
:
>>> L1 = ['a', 'b', 'c', 'd', 'e', 'f']
>>> L2 = ['a', 'e', 'i', 'o', 'u']
>>> for char in L1:
... if char not in L2:
... char
b
c
d
f
Compound expressions
Like aritmetic expressions, boolean expressions can be also grouped using parentheses to indicate the order of the operations.
if (a > b and b == 13) or b == 25:
# do something
if a > b and (b == 13 or b == 25):
# do something