标签:top 布尔类型 hat 类型 运算 one 错误 运算符 效率
python 中布尔值使用常量True 和 False来表示;注意大小写
比较运算符< > == 等返回的类型就是bool类型;布尔类型通常在 if 和 while 语句中应用
这边需要注意的是,python中,bool是int的子类(继承int),故 True==1 False==0 是会返回Ture的,有点坑,如要切实判断用 xxx is True
1 print(True==1) # 返回True 2 print(False==0) # 返回True 3 print(1 is True) 4 print(0 is False)
另外,还有几个坑。。。 如,Python2中True/False不是关键字,因此我们可以对其进行任意的赋值;同理,Python 中 if(True) 的效率远比不上 if(1)
True = "True is not keyword in Python2" # Python2 版本中True False不是关键字,可被赋值,Python3中会报错
另,由于bool是int,可进行数字计算 print(True+True)
以下会被判定为 False :
除了以上的,其他的表达式均会被判定为 True,这个需要注意,与其他的语言有比较大的不同。
1 print(bool()) 2 print(bool(False)) 3 print(bool(0),bool(0.0),bool(0j)) 4 print(bool(""),bool(()),bool([]),bool({})) 5 class alfalse(): 6 def __bool__(self): # 定义了 __bool__() 方法,始终返回False 7 return False 8 f = alfalse() 9 print(bool(f)) 10 class alzero(): 11 def __len__(self): # 定义了 __len__() 方法,始终返回0 12 return 0 13 zero = alzero() 14 print(bool(zero)) 15 class justaclass(): 16 pass 17 c = justaclass() 18 print(bool(c)) # 一般class instance都返回为True
Operation | Result |
---|---|
x or y | if x is false, then y, else x |
x and y | if x is false, then x, else y |
not x | if x is false, then True, else False |
注意均为小写: and or not ; 注意布尔运算的优先级低于表达式, not a == b 相当于 not (a == b), 若 a == not b 就会有语法错误
转载自:https://www.cnblogs.com/feeland/p/4360331.html
标签:top 布尔类型 hat 类型 运算 one 错误 运算符 效率
原文地址:https://www.cnblogs.com/DcentMan/p/11415808.html