# if一行 Python有三元条件运算符吗？

(falseValue, trueValue)[test]

test需要返回TrueFalse

(falseValue, trueValue)[test == True]

(falseValue, trueValue)[bool(<expression>)]
python三态

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

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

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

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

# 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

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

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] ;

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

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

#[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")

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