短絡評価

論理演算子と短絡評価

python の論理演算子

python のx and yは真偽値ではなく、xもしくはyを返す。

6.11. Boolean operations
The expression x 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 yxFalse
x or yxTrue のときyは評価されず、xが返り値になる。

x = None
y = "Default name"
print(x or y)
Default name

x = "Alice"
y = "Default name"
print(x or y)
Alice
Last modified 2020.11.23