python中的三元表達式的使用方法

python中的三元表達式的使用方法

python中沒有其他語言中的三元表達式,但是有類似的實現方法

格式:[on_true] if [expression] else [on_false]

res = 值1 if 條件 else 值2

a = 111
b = 555
res = ""
res = "我是最帥的" if a>b else "你是最帥的"
print(res)

運行結果:

你是最帥的

也可以使用簡單的公式

a = 111
b = 555
res = ""
res = a-b if a>b else a+b
print(res)

運行結果:

666


分享到:


相關文章: