python筆記之運算子
阿新 • • 發佈:2018-11-13
算數運算子
+ - * / % **
*
print(5 * 2)
/
print(5 / 2)
% 取餘
print(5 % 2)
** 冪
print(5 ** 2)
賦值運算子
num = 10
print(num)
== += -= *= /= %= **=
num **= 3 # num = num^3
print(num)
結果:
1000
比較運算子
運算結果是bool型別
> < >= <= !=
print(10 != 20)
邏輯運算子
多個條件表示式協同的結果
and or not
res = 10 > 20 and 3.14 < 6 # and 前結果要為真,
後結果也要為真,整體才為真,否則結果為假
print(res)
res = 10 > 20 or 3.14 <6 # or 前後都為假,整體為假
短路
邏輯運算子最終結果不一定為bool型別
0 空物件 空字串 等等代表空的為假,其他資料均為真
and 短路,and前為假時已經能決定整體為假,and後不需要解釋執行
res = 0 and 2
print(res)
執行結果:0
or 短路,or前為真時,已經能決定整體為真,or後面不需要解釋執行
res = -2 and 2
print(res)
執行結果為:2
not的用法
一般與if連用
判斷是否為None的情況
if not x
if x is None
if not x is None
使用if not x這種寫法的前提是:必須清楚x等於None, False, 空字串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行