捐助郴维网
感谢您对郴维网的支持,你的支持将是郴维网持续发展的动力!
二维码
×
当前位置:郴维网 >基础知识 > 正文
2 2018.03

布尔类型 bool

点击次数:1223 更新时间:2018/3/2 22:02:32  【打印此页

python 中布尔值使用常量True 和 False来表示;注意大小写

  比较运算符< > == 等返回的类型就是bool类型;布尔类型通常在 if 和 while 语句中应用

  这边需要注意的是,python中,bool是int的子类(继承int),故 True==1  False==0 是会返回Ture的,有点坑,如要切实判断用 xxx is True

print(True==1)                        # 返回True
print(False==0)                       # 返回True
print(1 is True)                    
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) 

 

True or False 判定

  以下会被判定为 False :

·         None

·         False

·         zero of any numeric type, for example, 0, 0.0, 0j.

·         any empty sequence, for example, '', (), [].

·         any empty mapping, for example, {}.

·         instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

  除了以上的,其他的表达式均会被判定为 True,这个需要注意,与其他的语言有比较大的不同。

print(bool())
print(bool(False))
print(bool(0),bool(0.0),bool(0j))
print(bool(""),bool(()),bool([]),bool({}))
class alfalse():
    def __bool__(self):           # 定义了 __bool__() 方法,始终返回False
        return False
f = alfalse()
print(bool(f))
class alzero():
    def __len__(self):            # 定义了 __len__() 方法,始终返回0
        return 0
zero = alzero()
print(bool(zero))
class justaclass():
    pass
c = justaclass()
print(bool(c))                    # 一般class instance都返回为True

 

布尔运算符 and   or   not

 

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 就会有语法错误

print((True and False),(False and False),(True and True))
print((True or False),(False or False),(True or True))
print((not True),(not False))
print( 1>1 and 1<1 )                 # 表达式优于bool运算  相当于 print( (1>1) and (1<1) )
print( (1>1 and 1)<1)                # 加括号了,值就不一样了
print(True and 1)                    # True and 数字,不建议这么使用,返回的是数字
print(True and 111)
print(False and 2)                   # False and 数字,返回False
print(not 1==1)
T = True
F = False
# print(T == not F)                  # 会报错
print(T == (not F))                  # 需加括号
提示
郴维网为您提供各类专业服务:
软件开发,电脑配件销售,WIFI路由器销售,上门电脑维修,上门安装系统,系统安装,软、硬件安装,电脑除尘清灰,显示器维修,WIFI安装调试,服务器维护,数据恢复,密码破解,网络布线,网络检修,打印机维修,打印机加碳粉,苹果电脑安装系统,苹果电脑安装双系统,监控安装维护,电脑外包,笔记本电脑维修,餐饮、美容行业软件安装 等。。。。。。
点击次数:1223 更新时间:2018/3/2 22:02:32  【打印此页
关键词推荐:郴州电脑城 郴州电脑维修公司 维修电脑公司 郴州软件开发 上门电脑维修 上门安装系统 笔记本电脑维修 郴州打印机维修 打印机加碳粉 电脑安装双系统 苹果电脑双系统 液晶显示器维修 联想笔记本维修 联想笔记本维修电话 戴尔笔记本维修电话 郴州戴尔笔记本维修 戴尔笔记本郴州维修点 华硕笔记本维修点 郴州华硕笔记本维修 郴州笔记本上网维修