Is it safe to replace '==' with 'is' to compare Boolean-values

前端 未结 7 2117
谎友^
谎友^ 2020-12-08 06:26

I did several Boolean Comparisons:

>>> (True or False) is True
True
>>> (True or False) == True
True

It sounds like

7条回答
  •  离开以前
    2020-12-08 06:44

    == and is are both comparison operators, which would return a boolean value - True or False. True has a numeric value of 1 and False has a numeric value of 0.

    The operator == compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator is tests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects.

    So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use is.

    42 is 42 is True and is same as 42 == 42.

提交回复
热议问题