Python: False vs 0

后端 未结 3 1967
傲寒
傲寒 2020-11-30 13:13

In PHP you use the === notation to test for TRUE or FALSE distinct from 1 or 0.

For example i

相关标签:
3条回答
  • 2020-11-30 13:17

    In Python,

    • The is operator tests for identity (False is False, 0 is not False).

    • The == operator which tests for logical equality (and thus 0 == False).

    Technically neither of these is exactly equivalent to PHP's ===, which compares logical equality and type - in Python, that'd be a == b and type(a) is type(b).

    Some other differences between is and ==:

    Mutable type literals

    • {} == {}, but {} is not {} (and the same holds true for lists and other mutable types)
    • However, if a = {}, then a is a (because in this case it's a reference to the same instance)

    Strings

    • "a"*255 is not "a"*255", but "a"*20 is "a"*20 in most implementations, due to how Python handles string interning. This behavior isn't guaranteed, though, and you probably shouldn't be using is in this case. "a"*255 == "a"*255 and is almost always the right comparison to use.

    Numbers

    • 12345 is 12345 but 12345 is not 12345 + 1 - 1 in most implementations, similarly. You pretty much always want to use equality for these cases.
    0 讨论(0)
  • 2020-11-30 13:31

    The strict equivalent of x === y in Python is type(x) is type(y) and x == y. You don't really want to do this as Python is duck typed. If an object has the appropriate method or attribute then you shouldn't be too worried about its actual type.

    If you are checking for a specific unique object such as (True, False, None, or a class) then you should use is and is not. For example: x is True.

    0 讨论(0)
  • 2020-11-30 13:40
    if something is False:
    

    is what you should do

    if something is None:
    

    also works

    the moral is use is ... (although you should never do something is 123457, or simillar)

    for why you should never do this with ints and things see http://ideone.com/iKmWCn

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