Python Basics – Boolean Operations

Boolean Operations

Boolean logic consists of operations done between True and False values :

  • and ( logical conjunction)
  • or ( logical disjunction)
  • not ( logical negation )

Object Evaluation

Evaluates as False

  • Constants : False and None
  • Numeric zero : 0 and 0.0
  • Lengths of zero : "" and []

Evaluates as True

  • everything else

The AND operator ( and )

It compares 2 operators and if they are true , it evaluates as true   :

  • True and True ==> True
  • True and False ==> False
  • False and False ==> False

The OR operator ( or )

  • False or True ==> True
  • True or True ==> True
  • False or False ==> False

The NOT operator ( not )

It returns the boolean opposite of an item following it

  • not True ==> False
  • not False ==> True

Order of Operations with NOT

It is lower in order

  • True == False ==> False
  • not True == False ==> True ( it negates the result of the operation, not the first item )

Object Evaluation

  • "CUSIP" and True ==> True
  • [] or False ==> False
  • not {} ==> True  ( empty dict results in False, but with NOT ==> True

Returning objects

  • AND operator  for 2 objects that are both True the last one is returned –> "State" and "Fed" > "State"
  • AND operator  for 2 objects where 1st one is False  the first one is returned –> [] and "Fed" > []
  • OR operator for 2 objects and 1st one is True, the first one is returned  –> 11 or "account" > 13
  • OR operator for 2 objects and 1st one is False, the second one is returned –> 0.0 or {'balance':2200} > {'balance':2200}

Example