チャポケのブログ

勉強したことをまとめておく。

Python 比較演算子

pythonの比較演算子

python比較演算子は、次の通り。

python演算子 その意味
x < y  x \lt y の場合、True
x > y  x \gt y の場合、True
x <= y  x \leqq y の場合、True
x >= y  x \geqq y の場合、True
x == y  x = y のように値が等しい場合、True
x != y  x \neq y のように値が異なる場合、True
x is y  x  y が同じオブジェクトの場合、True
x is not y  x  y が同じオブジェクトでない場合、True
x = 10
y = 15
print(x < y)      # True
print(x > y)      # False
print(x <= y)     # True
print(x >= y)     # False
print(x == y)     # False
print(x != y)     # True
print(x is y)     # False
print(x is not y) # True
x = 10
z = 10
print(x == z)     # True
print(x != z)     # False
print(x is z)     # True
print(x is not z) # False
x = 10
f = 10.0
print(x == f)     # True  整数型と浮動小数点数型だが、数値は等しい
print(x != f)     # False
print(x is f)     # False 整数型と浮動小数点数型で、同じオブジェクトではない
print(x is not f) # True

比較演算子の連結記述

この比較演算子は、"x < y < z" のように連結した記述が可能

y=15
print(0  <= y < 10) # False
print(10 <= y < 20) # True
print(20 <= y < 30) # False

"x < y < z" は、"x < y and y < z" とほぼ等価
"x < y < z" では、yは1回だけ評価されるが、
"x < y and y < z" では、yは2回評価される。 この分だけ違いがあるので注意が必要

#***** 等価になる例 *****
p=12
print(10 <= p < 20) # True
p=12
print(10 <= p and p < 20) # True


#***** 等価にならない例 *****
def test():
    global q
    q+=10
    return q

q=2
print(10 <= test() < 20) # True 
q=2
print(10 <= test() and test() < 20) # False
q=2
print(test()) # 12 ※1回目のtest()関数呼び出し
print(test()) # 22 ※2回目のtest()関数呼び出し