# Python是否有三元條件運算符？

``````(falseValue, trueValue)[test]
``````

`test`需要返回TrueFalse

``````(falseValue, trueValue)[test == True]
``````

``````(falseValue, trueValue)[bool(<expression>)]
``````
Question

``````In [1]: a = 1 if False else 0

In [2]: a
Out[2]: 0

In [3]: b = 1 if True else 0

In [4]: b
Out[4]: 1
``````

``````cond and on_true or on_false
``````

``````>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1
``````

``````>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>> print 0 if x == 0 else 1
1
``````

``````>>> a = False
>>> b = 5
>>> a or b
5

>>> a = None
>>> a or b
5
``````

# Python是否有三元條件運算符？

``````test: or_test ['if' or_test 'else' test] | lambdef
``````

``````or_test ['if' or_test 'else' test]
``````

``````expression1 if expression2 else expression3
``````

`expression3`將被延遲評估（即，只有在布爾上下文中`expression2`為false時才評估）。 由於遞歸定義，你可以無限期地鏈接它們（雖然它可能被認為是不好的風格）。

``````expression1 if expression2 else expression3 if expression4 else expression5 # and so on
``````

### 使用說明：

``````[expression1 if expression2 for element in iterable]
#                          ^-- need an else here
``````

``````[expression1 for element in iterable if expression2]
``````

`expression2`作為列表理解的過濾器， 並不是三元條件運算符。

### 更窄範圍的替代語法：

``````expression1 if expression1 else expression2
``````

`expression1`將不得不使用上面的用法評估兩次。 它可以限制冗餘，如果它只是一個局部變量。 然而，這種用例的一個常見和高性能的Pythonic慣用法是使用`or`是捷徑行為：

``````expression1 or expression2
``````

expression1 if condition else expression2

``````>>> a = 1
>>> b = 2
>>> 1 if a > b else -1
-1
>>> 1 if a > b else -1 if a < b else 0
-1
``````

``````if conditionX:
print('yes')
else:
print('nah')
``````

，變成：

``````print('yes') if conditionX else print('nah')
``````

``````[on_true] if [cond] else [on_false]
``````

``````cond and on_true or on_false
``````

``````{True: on_true, False: on_false}[cond is True] # is True, not == True
``````

``````def q(cond, on_true, on_false)
return {True: on_true, False: on_false}[cond is True]
``````

``````q(cond, on_true, on_false)
``````

``````<expression1> if <condition> else <expression2>
``````

``````if <condition>: <expression1> else: <expression2>
``````

``````result = x if a > b else y
``````

``````result = (lambda:y, lambda:x)[a > b]()
``````

``````result = (y, x)[a > b]
``````

``````result = {True: x, False: y}[a > b]
``````

``````result = (a > b) and x or y
``````

``````result = ((a > b) and [x] or [y])[0]
``````

``````result = ((a > b) and (x,) or (y,))[0]
``````

``````shell = os.environ.get('SHELL', "/bin/sh")
``````

``````>>> b = (True if 5 > 4 else False)
>>> print b
True
``````