短絡評価

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.

 1x = 'X' #True
 2y = 'Y' #True
 3
 4print(x and y)
 5Y
 6
 7print(x or y)
 8X
 9
10x = 'X' #True
11y = 0   #False
12
13print(x and y)
140
15
16print(x or y)
17X
18
19x = 0   #False
20y = 0.0 #False
21
22print(x and y)
230
24print(x or y)
250.0

真偽値が欲しいときはbool()関数

1x = 'X'
2y = 'Y'
3
4print(bool(x and y))
5True

短絡評価

x and yxFalse
x or yxTrue のときyは評価されず、xが返り値になる。

1x = None
2y = "Default name"
3print(x or y)
4Default name
5
6x = "Alice"
7y = "Default name"
8print(x or y)
9Alice