Python bool type bool

Boolean values ​​in python are represented by the constants True and False; pay attention to case

< > ==The type returned by comparison operators is the bool type; the bool type is usually used in if and while statements

It should be noted here that, python in, bool is a subclass of int (inherited int), it True==1 False==0will return Ture, a little pit, judgment as to effectivelyxxx is True

 print(True==1)                        # 返回True
 print(False==0)                       # 返回True
 print(1 is True)                    
 print(0 is False)

In addition, there are several pits. . . For example, True/False in Python2 is not a keyword, so we can assign any value to it; for the same reason, if(True) in Python is far less efficient than if(1)

True = "True is not keyword in Python2"        
# Python2 版本中True False不是关键字,可被赋值,Python3中会报错 

In addition, because bool is an int, numerical calculations can be performed print(True+True)

True or False judgment

The following will be judged as 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.

In addition to the above, other expressions will be judged as True. This needs to be noted, which is quite different from other languages.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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

Boolean operators and or not
Insert picture description here
attention lowercase: and or not; Note Boolean operations of lower priority than the expression, not a == bequivalent to not (a == b), if a == not bthere will be a syntax error

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))                  # 需加括号

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/109262252