Python 速查手冊

3.3 比較運算

比較運算是比較兩個運算元 (operand) 的關係,包括大於、小於、相等、不相等之類。

比較運算子有使用小於符號的小於,使用大於符號的大於,使用小於符號跟等號連結在一起的小於等於,使用大於符號跟等號連結在一起的大於等於,連續兩個等號為比較相等,驚嘆號加上等號則是比較不相等。這裡須注意由於單獨一個等號已經被當成指派運算子,因此比較相等用連續兩個等號。

符號作用
<小於
>大於
<=小於等於
>=大於等於
==相等
!=不相等

比較運算是布林運算的一種,結果回傳真假值,這裡可以看到 12 > 5 回傳 True6.7 > 8.9 回傳 False ,至於字串 (string) 的比較是比較第一個字元在字母表中的順序,字元在字母表越後面,表示該字元的數值越大,如果第一個字元相同,就會往後比較之後的字元,這裡 ThereThem 是比較第四個字元 rm ,由於 r 在字母表排在 m 之後,因此回傳 True

print(12 > 5)
print(6.7 > 8.9)
print("There" > "Them")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison01.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison01.py
True
False
True
$

繼續看到 12 < 5 回傳 False6.7 < 8.9 回傳 True"There" < "Them" 回傳 False

print(12 < 5)
print(6.7 < 8.9)
print("There" < "Them")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison02.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison02.py
False
True
False
$

12 >= 5 回傳 True6.7 >= 6.7 回傳 True"There" >= "Them" 回傳 True

print(12 >= 5)
print(6.7 >= 6.7)
print("There" >= "Them")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison03.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison03.py
True
True
True
$

12 <= 5 回傳 False6.7 <= 6.7 回傳 True"There" <= "Them" 回傳 True

print(12 <= 5)
print(6.7 <= 6.7)
print("There" <= "Them")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison04.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison04.py
False
True
False
$

12 == 5 回傳 False6.7 == 6.7 回傳 True ,字串的比較相等則會做逐字元比較,因此 "There" == "Them" 回傳 False"There" == "There" 回傳 True

print(12 == 5)
print(6.7 == 6.7)
print("There" == "Them")
print("There" == "There")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison05.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison05.py
False
True
False
True
$

12 != 5 回傳 True6.7 != 6.7 回傳 False"There" != "Them" 回傳 True"There" != "There" 回傳 False

print(12 != 5)
print(6.7 != 6.7)
print("There" != "Them")
print("There" != "There")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:comparison06.py
# 功能:示範比較運算
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 comparison06.py
True
False
True
False
$

相關教學影片

上一頁: 3.2 位元運算
Python 速查手冊 - 目錄
下一頁: 3.4 指派運算
回 Python 教材首頁
回程式語言教材首頁