Python 的條件語句(if?語句)是控制程序流程的基礎之一,結構清晰、語法簡潔,非常適合初學者掌握。
一、基本語法結構
if 條件:執行代碼塊1
elif 條件2:執行代碼塊2
else:執行代碼塊3
示例:
score = 85if score >= 90:print("優秀")
elif score >= 60:print("及格")
else:print("不及格")
二、條件表達式的寫法(支持各種比較)
表達式 | 含義 |
---|---|
a == b | 等于 |
a != b | 不等于 |
a > b,?a < b | 大于 / 小于 |
a >= b,?a <= b | 大于等于 / 小于等于 |
a in list | a?是否在列表中 |
a not in list | a?不在列表中 |
x is y,?x is not y | 判斷對象是否相同(同一地址) |
bool(變量) | 判斷變量是否為真(非空、非0等) |
三、簡潔寫法:單行 if 和三元表達式
1. 單行?if:
x = 10
if x > 5: print("大于5")
2. 三元表達式(類似 Java 的?? :):
result = "及格" if score >= 60 else "不及格"
四、邏輯運算符(可組合條件)
關鍵字 | 說明 |
---|---|
and | 且,兩個條件都為真 |
or | 或,只要一個為真即可 |
not | 非,邏輯取反 |
示例:
age = 20
gender = "male"if age > 18 and gender == "male":print("成年男性")
五、常用技巧
1. 判斷多個值
if fruit in ("apple", "banana", "orange"):print("是常見水果")
2. 空值判斷(None、空字符串、空列表等)
name = ""
if not name:print("名字不能為空")
3. 使用?match(Python 3.10+ 新增結構化匹配)
command = "start"match command:case "start":print("啟動中")case "stop":print("停止中")case _:print("未知命令")
六、布爾類型與隱式轉換
在條件判斷中,以下值會被視為?False:
- None
- False
- 0、0.0
- 空字符串?""
- 空列表?[]、空元組?()、空字典?{}、空集合?set()
if not []:print("這是個空列表") # 會執行
七、嵌套條件判斷
if score >= 60:if score >= 90:print("優秀")else:print("及格")
else:print("不及格")