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
andNone
- Numeric zero :
0
and0.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
# Print the given variables is_investment_account = True balance_positive = True print(is_investment_account) print(balance_positive) > True > True # Decide if this account is candidate for trading advice potential_trade = is_investment_account and balance_positive # Print if this represents a potential trade print(potential_trade) > True
# Assign a default action if no input input_action = '' is_trading_day = False action = input_action or "Hold" # Print the action print(action) > 'Hold' # Assign action only if trades can be made do_action = is_trading_day and action # Print the action to do print(do_action) >'False'
closing_prices = [] market_closed = False print(closing_prices) > [] # Assigning True if we need to get the prices not_prices = not closing_prices print(not_prices) > True # Get prices if market is closed and we don't have prices get_prices = not (market_closed and not_prices) print(get_prices) > True