Why in Python does “0, 0 == (0, 0)” equal “(0, False)”?

后端 未结 7 933
粉色の甜心
粉色の甜心 2020-12-04 09:20

In Python (I checked only with Python 3.6 but I believe it should hold for many of the previous versions as well):

(0, 0) == 0, 0   # results in a two elemen         


        
相关标签:
7条回答
  • 2020-12-04 10:17

    I had a similar question. I am not a computer scientist, I am either a software engineer or a computer programmer. So I asked the python interpreter and this is what I found, empirically.

    >>> t1 = ()
    >>> "True" if t1 else "False"
    'False'
    >>> t1 = (False)     # That's because t1 is not a tuple!
    >>> "True" if t1 else "False"
    'False'
    >>> t1 = (False,)     # t1 is a tuple.  So , is an operator as mentioned above
    >>> "True" if t1 else "False"
    'True'
    >>> t1 = (False, 1)
    >>> "True" if t1 else "False"
    'True'
    >>> t1 = (False, False)
    >>> "True" if t1 else "False"
    'True'
    >>> type(False,)
    <class 'bool'>
    >>> type((False,))
    <class 'tuple'>
    >>> type(False)
    <class 'bool'>
    >>> type((False))
    <class 'bool'>
    >>>
    
    

    I did a lot of testing and the only tuple I found that evaluate to False is the empty tuple.

    I also learned something in this exercise. A lot of rookies use the idiom:

    if BOOLEAN_EXPRESSION == False:
    

    instead of

    if not BOOLEAN_EXPRESSION:
    

    "Why is this a bad thing to do?", they ask me. Now, I have a good answer:

    >>> (False,) == False
    False
    >>> t1=(False,)
    >>> "True" if t1 else "False"
    'True'
    >>> t1 == False
    False
    >>>
    >>> t1=(False,)
    >>> "True" if t1 else "False"
    'True'
    >>> t1 == False
    False
    >>> t1 is False
    False
    >>> not t1 is False
    True
    >>> not ( t1 is False )
    True
    >>>
    >>> "True" if t1 else "False"
    'True'
    >>> "True" if not t1 else "False"
    'False'
    >>> "True" if t1 == True else "False"
    'False'
    >>>
    
    
    

    So even though (False,) evaluates to False, it is not False.

    I would like to thank you for asking this question to my attention. It's a great question.

    0 讨论(0)
提交回复
热议问题