Why does … == True return False in Python 3?

后端 未结 4 1558
自闭症患者
自闭症患者 2021-02-08 01:53

I am learning python, but I\'m a bit confused by the following result.

In [41]: 1 == True
Out[41]: True

In [42]: if(1):
    ...:     print(\'111\')
    ...:             


        
4条回答
  •  -上瘾入骨i
    2021-02-08 02:25

    In python most (all?) objects have a bool value. The meaning behind "has a truth value of True" means that bool(obj) evaluates to True.

    On the other hand, True is treated as 1 in many cases (and False as 0) which you can see when you do stuff like:

    sum([True, True, False])
    # (1 + 1 + 0) -> 2
    

    That is why you get 1 == True --> True

    There is a more explicit explanation in the documentation:

    Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true). In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively

    From the type-hierarchy itself in the docs:

    These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

提交回复
热议问题