# Boolean Operations: and, or, not¶

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

In :
(True and True, True and False, False and False)

Out:
(True, False, False)
In :
(True or True, True or False, False or False)

Out:
(True, True, False)
In :
(not True, not False)

Out:
(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 :
True and (10 // 0 == 0)

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
----> 1 True and (10 // 0 == 0)

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

Out:
False
In :
True or (10 // 0 == 0)

Out:
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 :
a = 42   # 00101010
b = 51   # 00110011
a & b    # 00100010

Out:
34
In :
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 :
(bin(42), bin(51), bin(34))

Out:
('0b101010', '0b110011', '0b100010')

## Why does & "works" with booleans?¶

In :
(True & False, True & True, False & False)

Out:
(False, True, False)

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

In :
(bin(True), bin(False))

Out:
('0b1', '0b0')

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

In :
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 :
False and (10 // 0 == 0)

Out:
False