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

后端 未结 4 1561
自闭症患者
自闭症患者 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条回答
  •  难免孤独
    2021-02-08 02:19

    Any object can be tested for "truthiness":

    Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered 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. [1]

    All other values are considered true — so objects of many types are always true.

    Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

    So it's not hard to see that if ... will enter the branch. The Ellipsis object is considered true. However that doesn't mean it has to be equal to True. Just the bool(...) == True!

    The if will implicitly call bool on the condition, so:

    if ...:
        # something
    

    will be evaluated as if you had written:

    if bool(...):
        # something
    

    and:

    >>> bool(...)
    True
    >>> bool(1)
    True
    >>> bool(2)
    True
    

    However there's one catch here. True is equal to 1 and False equal to 0, but that's just because bool subclasses integer in python.

提交回复
热议问题