Python 真值測試
什麼是真值
我們可以使用任何物件來測試真值。透過在 if 或 while 語句中提供條件,可以進行檢查。
除非類方法 __bool__() 返回 False 或 __len__() 方法返回 0,否則我們可以認為該物件的真值為 True。
當常量的值為 False 或 None 時,其值為 False。
當變數包含不同的值,例如 0、0.0、Fraction(0, 1)、Decimal(0)、0j 時,它表示 False 值。
空序列 ‘‘、[]、()、{}、set(0)、range(0) 的真值均為 False。
1 和 0 的真值
真值 0 等效於 False,而 1 等效於 True。讓我們看看真值,即 1 的真值為 True:
a = 1, then bool(a) = True
讓我們看看真值的相反情況,即 0 的真值為 False:
a = 0, then bool(a) = False
讓我們再看一個簡單的例子。1 的真值為 True:
a = 1 if(a==1) print(“True”)
0 的真值為 False:
a = 0 if(a==0) print(“False”)
Python 真值測試示例
讓我們看一個完整的例子:
示例
class A: # The class A has no __bool__ method, so default value of it is True def __init__(self): print('This is class A') a_obj = A() if a_obj: print('It is True') else: print('It is False') class B: # The class B has __bool__ method, which is returning false value def __init__(self): print('This is class B') def __bool__(self): return False b_obj = B() if b_obj: print('It is True') else: print('It is False') myList = [] # No element is available, so it returns False if myList: print('It has some elements') else: print('It has no elements') mySet = (10, 47, 84, 15) # Some elements are available, so it returns True if mySet: print('It has some elements') else: print('It has no elements')
輸出
This is class A It is True This is class B It is False It has no elements It has some elements
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP