Comparison operators

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Python comparison operators

  • Equality: ==,!=
  • Order: <,>,<=,>=
Intermediate Python for Finance

Equality operator vs assignment

Test equality: ==

Assign value: =

Intermediate Python for Finance

Equality operator vs assignment

13 == 13
True
count = 13
print(count)
13
Intermediate Python for Finance

Equality comparisons

  • datetimes
  • numbers (floats, ints)
  • dictionaries
  • strings
  • almost anything else
Intermediate Python for Finance

Comparing datetimes

date_close_high = datetime(2019, 11, 27)
date_intra_high = datetime(2019, 11, 27)
print(date_close_high == date_intra_high)
True
Intermediate Python for Finance

Comparing dictionaries

d1 = {'high':56.88, 'low':33.22, 'closing':56.88}
d2 = {'high':56.88, 'low':33.22, 'closing':56.88}
print(d1 == d2)
True
d1 = {'high':56.88, 'low':33.22, 'closing':56.88}
d2 = {'high':56.88, 'low':33.22, 'closing':12.89}
print(d1 == d2)
False
Intermediate Python for Finance

Comparing different types

print(3 == 3.0)
True
print(3 == '3')
False
Intermediate Python for Finance

Not equal operator

print(3 != 4)
True
print(3 != 3)
False
Intermediate Python for Finance

Order operators

  • Less than <
  • Less than or equal <=
  • Greater than >
  • Greater than or equal >=
Intermediate Python for Finance

Less than operator

print(3 < 4)
True
print(3 < 3.6)
True
print('a' < 'b')
True
Intermediate Python for Finance

Less than operator

date_close_high = datetime(2019, 11, 27)
date_intra_high = datetime(2019, 11, 27)
print(date_close_high < date_intra_high)
False
Intermediate Python for Finance

Less than or equal operator

print(1 <= 4)
True
print(1.0 <= 1)
True
print('e' <= 'a')
False
Intermediate Python for Finance

Greater than operator

print(6 > 5)
print(4 > 4)
True
False
Intermediate Python for Finance

Greater than or equal operator

print(6 >= 5)
print(4 >= 4)
True
True
Intermediate Python for Finance

Order comparison across types

print(3.45454 < 90)
True
print('a' < 23)
<hr />----------------------------------------------
TypeError      Traceback (most recent call last)
...
TypeError: '<' not supported between instances of 'str' and 'int'
Intermediate Python for Finance

Let's practice!

Intermediate Python for Finance

Preparing Video For Download...