真值測試
所謂真值測試,是指當一種型別物件出現在if或者while條件語句中時,物件值表現為true或者false。弄清楚各種情況下的真值對我們編寫程式有重要的意義。
對於乙個物件a,其真值定義為:
true : 如果函式truth_test(a)返回true。
false:如果函式truth_test(a)返回false。
以if為例(while是等價的,不做贅述),定義函式truth_test(x)為:
def truth_test(x):
if x:
return true
else:
return false
2.物件的真值測試
一般而言,對於乙個物件,在滿足以下條件之一時,真值測試為false;否則真值測試為true。
其內建函式bool()返回false
其內建函式len()返回0
(1)以下型別物件真值測試為真:
class x:
pass
(2)以下真值測試為假:
class y:
defbool(self):
return false
(3)以下真值測試為假:
class z:
deflen(self):
return 0
進入python3指令碼環境,測試過程如下:
class x:… pass
… class y:
… defbool(self):
… return false
… class z:
… deflen(self):
… return 0
… def truth_test(x):
… if x:
… return true
… else:
… return false
… x = x()
y = y()
z = z()
truth_test(x)
true
truth_test(y)
false
truth_test(z)
false
常見物件的真值
下面是常見的真值為false的情況:
常量:none and false.
數值0值: 0, 0.0, 0j, decimal(0), fraction(0, 1)
序列或者集合為空:」, (), , {}, set(), range(0)
進入python3指令碼環境,測試過程如下:
truth_test(none)false
truth_test(false)
false
truth_test(0)
false
truth_test(0.0)
false
truth_test(0j) #複數
false
truth_test(decimal(0)) #十進位制浮點數
false
truth_test(fraction(0,1)) #分數
false
truth_test(fraction(0,2)) #分數
false
truth_test(」)
false
truth_test(())
false
truth_test({})
false
truth_test(set())
false
truth_test(range(0)) #序列
false
truth_test(range(2,2)) #序列
false
此外的其它取值,真值測試應當為true。
4.一些有意思的例子
下面是一些有意思的例子,原理不超出前面的解釋。
if 1 and fraction(0,1):… print(true)
… else:
… print(false)
… false
if 1 and ():
… print(true)
… else:
… print(false)
… false
if 1 and range(0):
… print(true)
… else:
… print(false)
… false
if 1 and none:
… print(true)
… else:
… print(false)
… false
if 1+2j and none:
… print(true)
… else:
… print(false)
… false
詳解python3中的真值測試
1.真值測試 所謂真值測試,是指當一種型別物件出現在if或者while條件語句中時,物件值表現為true或者false。弄清楚各種情況下的真值對我們編寫程式有重要的意義。對於乙個物件a,其真值定義為 以if為例 while是等價的,不做贅述 定義函式truth test x 為 def truth ...
Web 介面測試 Python3
usr bin env python3 coding utf 8 author leo date time 2020 5 28 and 15 44 project python3 filename 20200528 email.py description qq郵件傳送 import smtplib...
Web 介面測試 Python3
usr bin env python3 coding utf 8 author leo date time 2020 2 24 and 17 29 project python3 filename tmp comment.py description 1.快速構造請求頭 1 2 1 3 1 kwar...