# 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 or expression2
``````

## 三元運算符在不同的編程語言中

Javascript中的三元運算符

``````var a = true ? 1 : 0;
# 1
var b = false ? 1 : 0;
# 0
``````

Ruby中的三元運算符

``````a = true ? 1 : 0
# 1
b = false ? 1 : 0
# 0
``````

Scala中的三元運算符

``````val a = true ? 1 | 0
# 1
val b = false ? 1 | 0
# 0
``````

R編程中的三元運算符

``````a <- if (TRUE) 1 else 0
# 1
b <- if (FALSE) 1 else 0
# 0
``````

Python中的三元運算符

``````a = 1 if True else 0
# 1
b = 1 if False else 0
# 0
``````

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
``````

### 句法 ：

[on_true] if [expression] else [on_false]

### 1-使用三元運算符的簡單方法：

``````# Program to demonstrate conditional operator
a, b = 10, 20
# Copy value of a in min if a < b else copy b
min = a if a < b else b
print(min)  # Output: 10
``````

### 2-直接使用元組，字典和lambda的方法：

``````# Python program to demonstrate ternary operator
a, b = 10, 20
# Use tuple for selecting an item
print( (b, a) [a < b] )
# Use Dictionary for selecting an item
print({True: a, False: b} [a < b])
# lamda is more efficient than above two methods
# because in lambda  we are assure that
# only one expression will be evaluated unlike in
# tuple and Dictionary
print((lambda: b, lambda: a)[a < b]()) # in output you should see three 10
``````

### 3-三元運算符可以寫為嵌套if-else：

``````# Python program to demonstrate nested ternary operator
a, b = 10, 20
print ("Both a and b are equal" if a == b else "a is greater than b"
if a > b else "b is greater than a")
``````

``````# Python program to demonstrate nested ternary operator
a, b = 10, 20
if a != b:
if a > b:
print("a is greater than b")
else:
print("b is greater than a")
else:
print("Both a and b are equal")
# Output: b is greater than a
``````

## 以下是它的工作原理：

``````0 and exp
``````

``````1 or exp
``````

``````True and exp1 or exp2
``````

``````False and exp1 or exp2
``````

### `[condition] and ([expression_1] or 1) or [expression_2] ;`

``````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
``````

``````[expression] and [on_true] or [on_false]
``````

`on_true`具有false布爾值時，它可能會給出錯誤的結果。 1

``````[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)
``````

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

`test`需要返回TrueFalse

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

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

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

``````a if condition else b
``````

``````>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
``````

``````>>> pass if False else x = 3
File "<stdin>", line 1
pass if False else x = 3
^
SyntaxError: invalid syntax
``````

• 參數的順序與許多其他語言（例如C，Ruby，Java等）不同，當不熟悉Python的“驚人”行為的人使用它時（可能會顛倒順序），這可能會導致錯誤。
• 有些人覺得它“笨拙”，因為它與正常的思想流程相反（首先考慮條件然後考慮影響）。
• 文體的原因。

``````is_fat = True
state = "fat" if is_fat else "not fat"
``````

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

，成為：

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

``````a, b, x, y = 1, 2, 'a greather than b', 'b greater than a'
result = (lambda:y, lambda:x)[a > b]()
``````

``````'b greater than a'
``````

``````[on_true] if [expression] else [on_false]
``````

``````x, y = 25, 50
big = x if x < y else y
print(big)
``````

``````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
``````