基本类型转换bool类型的规律

bool类型只有两种结果True或False

那么向数字,字符串等一些基本类型转换为bool型的规律是什么

数字0为假,非0为真
字符串空为假,其他为真
元组、列表、字典、集合空为假,只有有元素就为真

创建空列表: list = []

创建空元组:tuple = (), t1 = tuple()

创建单个元素的元组:tuple_single = (‘1’,)

创建空字典: dict = {}

创建空集合:set = set()

a = 3
b = 0
c = -3
d = 0.0
print("\na = ",a,bool(a),"b =",b,bool(b))
print("\nc = ",c,bool(c),"d =",d,bool(d))
a = "abc"
b = ""
print("\na = ",a,bool(a),"b =  ",b,bool(b))
a = [1]
b = []
print("\na = ",a,bool(a),"b =",b,bool(b))
a = (1,)
b = tuple()
print("\na = ",a,bool(a),"b =",b,bool(b))
a = {1:100}
b = {}
print("\na = ",a,bool(a),"b =",b,bool(b))
a = {1}
b = set()
print("\na = ",a,bool(a),"b =",b,bool(b))

基本类型转换bool类型的规律_第1张图片

你可能感兴趣的:(python)