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

例如,根據成績判斷學生是否及格,

1
2
3
score = 75
status = "及格" if score >= 60 else "不及格"
print(status)

以下範例將提供了更多使用三元運算子的情境,讓你在程式碼中更靈活地處理條件判斷。

Python 三元運算子範例:max 取最大值

這邊舉個 Python 三元運算子 ternary operator 的範例,寫一個 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

Python 三元運算子範例:判斷奇偶數

這邊另外舉個 Python 三元運算子來判斷奇偶數的範例,

1
2
3
num = 7
result = "奇數" if num % 2 != 0 else "偶數"
print(result)

輸出結果如下:

1
奇數

Python 三元運算子範例:檢查是否為正數、負數或零

Python 三元運算子還可以用來檢查是否為正數、負數或零,範例如下,

1
2
3
value = -3
result = "正數" if value > 0 else ("零" if value == 0 else "負數")
print(result)

輸出結果如下:

1
負數

下一篇介紹 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