短絡評価
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.
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 y
でx
がFalse
x or y
でx
がTrue
のときy
は評価されず、x
が返り値になる。
1x = None
2y = "Default name"
3print(x or y)
4Default name
5
6x = "Alice"
7y = "Default name"
8print(x or y)
9Alice