# 三元運算子英文 Python有三元條件運算符嗎?

## 三元運算子英文 (19)

``````general syntax : first_expression if bool_expression_is_true else second_expression

Example: x= 3 if 3 > 2 else 4
# assigns 3 to x if the boolean expression evaluates to true or 4 if it is false
``````

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

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

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

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

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

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

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

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

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

### 句法 ：

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

@up：

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

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

（執行延遲到獲勝者已知;）），但它引入了可調用和不可調用對象之間的不一致。 此外，它不能解決使用屬性時的情況。

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

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

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

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

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

``````def test(myvar=None):
# shorter than: print myvar if myvar else "no Input"
print myvar or "no Input"

test()
test([])
test(False)
test('hello')
test(['Hello'])
test(True)
``````

``````no Input
no Input
no Input
hello
['Hello']
True
``````

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

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

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

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

`test`需要返回TrueFalse

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

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

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

，成為：

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

``````#[On true] if [expression] else[On false]
# if the expression evaluates to true then it will pass On true otherwise On false

a= input("Enter the First Number ")
b= input("Enter the Second Number ")

print("A is Bigger") if a>b else print("B is Bigger")
``````