Python 三元運算子 ternary operator

在 python 使用三元運算子(ternary conditional operator) 好處是程式碼可以看起來比較簡短,
在某些情況 python 使用三元運算子簡化後 code 會變得清爽簡短許多。

如果是 C 的寫法像下面這樣

1
flag ? true : false

Python 的寫法

那 python 的寫法呢?只有下列寫法最接近。

1
flag = True if x.isClick() else False

跟下列寫法相同

1
2
3
4
if x.isClick():
flag = True
else:
flag = False

接下來認真學習一下三元運算子的語法,
Python 三元運算子 ternary operator 的語法如下:

1
condition_is_true if condition else condition_is_false

其它常用範例. max 取最大值

python-ternary-operator-max.py
1
2
3
4
5
6
7
8
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

def max(a, b):
return a if a > b else b

print(max(1, 2))
print(max(3, 5))

輸出結果如下:

1
2
2
5

下一篇介紹 and 的用法

以上就是 Python 三元運算子 ternary operator 介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

參考
[1] Does Python have a ternary conditional operator?
https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator
[2] 6. Ternary Operators — Python Tips 0.1 documentation
http://book.pythontips.com/en/latest/ternary_operators.html
[3] Ternary Operator in Python - GeeksforGeeks
https://www.geeksforgeeks.org/ternary-operator-in-python/

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例
Python 計算程式執行時間
在 RPi3 上寫 Bluetooth 程式 (Python)
Python 圖片模糊化 blur
Python 旋轉圖片 rotate