比較運算子

Intermediate Python for Finance

Kennedy Behrman

Data Engineer, Author, Founder

Python 比較運算子

  • 相等: ==,!=
  • 大小關係: <,>,<=,>=
Intermediate Python for Finance

相等運算子 vs 指派

測試相等: ==

指定數值: =

Intermediate Python for Finance

相等運算子 vs 指派

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

相等比較

  • 日期時間
  • 數值(floats、ints)
  • 字典
  • 字串
  • 幾乎所有其他型別
Intermediate Python for Finance

比較日期時間

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

比較字典

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

跨型別比較

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

不相等運算子

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

大小比較運算子

  • 小於 <
  • 小於或等於 <=
  • 大於 >
  • 大於或等於 >=
Intermediate Python for Finance

小於運算子

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

小於運算子

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

小於或等於運算子

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

大於運算子

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

大於或等於運算子

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

跨型別的大小比較

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

一起來練習吧!

Intermediate Python for Finance

Preparing Video For Download...