Python Basics – Comparison Operators

Comparison Operators

  • Equality :  == , !=
  • Order: < , > , <= , >=

Assignment Operator

  • Assignment : =

 

13 == 13
> True
count = 13
print(count)
> 13

Equality Comparisons

  • datetimes
  • numbers ( float / int )
  • dictionaries
  • strings
# Comparing dictionaries
d1 = {'high':56.78,'low':33.24,'closing':56.77}
d2 = {'high':56.78,'low':33.24,'closing':56.77}
print(d1 == d2)
> True

d1 = {'high':56.78,'low':33.24,'closing':56.77}
d2 = {'high':56.78,'low':33.24,'closing':46.01}
print(d1 == d2)
> False

Comparing different types

# Comparing int vs float 
print(3 == 3.0) 
> True

# comparing int vs string
print(3 == '3')
> False


Not equal operator

print(3 != 4)
> True

print( 3 != 3)
> False

Order operators

  • Less than <
  • Less than or equal <=
  • Greater than >
  • Greater than or equal >=

 

print(3 < 4)
> True
print(3 < 3.6)
> True
print('a' < 'b')
> True

date_close_high = datetime(2019,11,27)
date_intra_high = datetime(2019,11,27)
print(date_close_high < date_intra_high)
> False

print(1 < 4)
> True
print(1.0 <= 1)
> True
print('e' < 'a')
> False

print(6 > 5)
> True
print(4 > 4)
> False
print(4 >= 4)
> True

 

Order comparisons across types

# float vs int)
print(3.1415 < 90)
True

# string vs int
print('a' < 23)
> TypeError

Examples

non_cash = 20.33
cash = 19.11

# Assign a value to cash.
cash = 19.11

# Check if cash is equal to non-cash
print(cash == non_cash)
> False
# Assign the value of cash to be equal non-cash
cash = non_cash
# Check if cash is equal to non-cash
print(cash == non_cash)
> True