>>> pass if False else passFile "<stdin>", line 1pass if False else pass^SyntaxError: invalid syntax
>>> # Python parses this as `x = (1 if False else y) = 2`>>> # The `(1 if False else x)` part is actually valid, but>>> # it can't be on the left-hand side of `=`.>>> x = 1 if False else y = 2File "<stdin>", line 1SyntaxError: cannot assign to conditional expression
>>> # If we parenthesize it instead...>>> (x = 1) if False else (y = 2)File "<stdin>", line 1(x = 1) if False else (y = 2)^SyntaxError: invalid syntax
# Invalid syntax: we didn't specify what the value should be if the# condition isn't met. It doesn't matter if we can verify that# ahead of time.a if True
但是,您可以使用条件表达式来分配变量,如下所示:
x = a if True else b
例如,返回一个值:
# Of course we should just use the standard library `max`;# this is just for demonstration purposes.def my_max(a, b):return a if a > b else b
# Program to demonstrate conditional operatora, b = 10, 20# Copy value of a in min if a < b else copy bmin = a if a < b else bprint(min) # Output: 10
2-直接使用元组、字典和lambda的方法:
# Python program to demonstrate ternary operatora, b = 10, 20# Use tuple for selecting an itemprint( (b, a) [a < b] )# Use Dictionary for selecting an itemprint({True: a, False: b} [a < b])# lambda is more efficient than above two methods# because in lambda we are assure that# only one expression will be evaluated unlike in# tuple and Dictionaryprint((lambda: b, lambda: a)[a < b]()) # in output you should see three 10
3-三元运算符可以写成嵌套的if-else:
# Python program to demonstrate nested ternary operatora, b = 10, 20print ("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 operatora, b = 10, 20if 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
#[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")
f = lambda x,y: 'greater' if x > y else 'less' if y > x else 'equal'
array = [(0,0),(0,1),(1,0),(1,1)]
for a in array:x, y = a[0], a[1]print(f(x,y))
# Output is:# equal,# less,# greater,# equal
a = 0b = 1
# Instead of this:x = a if a else b# Evaluates as 'a if bool(a) else b'
# You could use short-circuit evaluation:x = a or b
短路评估的一个主要优点是链接两个以上表达式的可能性:
x = a or b or c or d or e
当使用函数时,它在细节上更不同:
# Evaluating functions:def foo(x):print('foo executed')return x
def bar(y):print('bar executed')return y
def blubb(z):print('blubb executed')return z
# Ternary Operator expression 1 equals to Falseprint(foo(0) if foo(0) else bar(1))''' foo and bar are executed oncefoo executedbar executed1'''
# Ternary Operator expression 1 equals to Trueprint(foo(2) if foo(2) else bar(3))''' foo is executed twice!foo executedfoo executed2'''
# Short-circuit evaluation second equals to Trueprint(foo(0) or bar(1) or blubb(2))''' blubb is not executedfoo executedbar executed1'''
# Short-circuit evaluation third equals to Trueprint(foo(0) or bar(0) or blubb(2))'''foo executedbar executedblubb executed2'''
# Short-circuit evaluation all equal to Falseprint(foo(0) or bar(0) or blubb(0))''' Result is 0 (from blubb(0)) because no value equals to Truefoo executedbar executedblubb executed0'''