Boolean Operations: and, or, not

and, or, not are boolean operators: use them in your boolen expressions!

In [1]:
(True and True, True and False, False and False)
Out[1]:
(True, False, False)
In [2]:
(True or True, True or False, False or False)
Out[2]:
(True, True, False)
In [3]:
(not True, not False)
Out[3]:
(False, True)

Reminder

Both binary operators and and or are short-circuit operators: if the first argument is sufficient to give the result, the second one is not evaluated.

In [4]:
True and (10 // 0 == 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-4-1770614f95ad> in <module>()
----> 1 True and (10 // 0 == 0)

ZeroDivisionError: integer division or modulo by zero
In [5]:
False and (10 // 0 == 0)
Out[5]:
False
In [6]:
True or (10 // 0 == 0)
Out[6]:
True

Bitwise Operations: & | ~

& | ~ are bitwise operators: they operate on integers (normally), but work on the bits of the binary twos-complement representation.

  • x & y is bitwise and of x and y
  • x | y is bitwise or of x and y
  • ~x inverts the bits of x

Bitwize and: &

'&' puts a bit 1 to the result if it exists in both operands:

binary
a = 42 0 0 1 0 1 0 1 0
b = 51 0 0 1 1 0 0 1 1
a & b 0 0 1 0 0 0 1 0
In [7]:
a = 42   # 00101010
b = 51   # 00110011
a & b    # 00100010
Out[7]:
34
In [8]:
help(bin)
Help on built-in function bin in module builtins:

bin(...)
    bin(number) -> string
    
    Return the binary representation of an integer.
    
       >>> bin(2796202)
       '0b1010101010101010101010'

In [9]:
(bin(42), bin(51), bin(34))
Out[9]:
('0b101010', '0b110011', '0b100010')

Why does & "works" with booleans?

In [10]:
(True & False, True & True, False & False)
Out[10]:
(False, True, False)

When & has boolean operands, it considers them as integers :(

In [11]:
(bin(True), bin(False))
Out[11]:
('0b1', '0b0')

But you should not use &, |, nor ~ as boolean operators !

In [12]:
False & (10 // 0 == 0)
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-12-56a6a32f273f> in <module>()
----> 1 False & (10 // 0 == 0)

ZeroDivisionError: integer division or modulo by zero
In [13]:
False and (10 // 0 == 0)
Out[13]:
False