短絡評価
論理演算子と短絡評価
python の論理演算子
python のx and y
は真偽値ではなく、x
もしくはy
を返す。
6.11. Boolean operations
The expressionx and y
first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.The expression
x or y
first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
x = 'X' #True
y = 'Y' #True
print(x and y)
Y
print(x or y)
X
x = 'X' #True
y = 0 #False
print(x and y)
0
print(x or y)
X
x = 0 #False
y = 0.0 #False
print(x and y)
0
print(x or y)
0.0
真偽値が欲しいときはbool()
関数
x = 'X'
y = 'Y'
print(bool(x and y))
True
短絡評価
x and y
でx
がFalse
x or y
でx
がTrue
のときy
は評価されず、x
が返り値になる。
x = None
y = "Default name"
print(x or y)
Default name
x = "Alice"
y = "Default name"
print(x or y)
Alice