Home python Is there a strict comparison statement in Python like ===?

Is there a strict comparison statement in Python like ===?

Author

Date

Category

just the usual comparison via == works not as needed:

& gt; & gt; & gt; 0 == False
True.

Answer 1, Authority 100%

If the essence of the question in comparing the values ​​and types, you can do this:

def strict_eq (obj1, obj2):
  IF Type (OBJ1)! = Type (OBJ2):
    Return False.
  RETURN OBJ1 == OBJ2

in [4]: ​​strict_eq (0, false)
Out [4]: ​​False

PS You can go even further for numerical types to compare the numbers to a certain accuracy to avoid known floating point problems:

in [5]: 0.1 + 0.2 == 0.3
Out [5]: False

Strict comparison function with a certain accuracy:

from numbers import number
DEF STRICT_EQ (OBJ1, OBJ2, EPSILON = 1E-7):
  IF Type (OBJ1)! = Type (OBJ2):
    Return False.
  IF IsInstance (OBJ1, Number):
    RETURN ABS (OBJ1 - OBJ2) & LT; Epsilon.
  RETURN OBJ1 == OBJ2

in [10]: strict_eq (0.1 + 0.2, 0.3)
Out [10]: True

Answer 2, Authority 7%

For many cases it is possible to apply a comparison ID s:

ID (0) == ID (FALSE)
false

It does not quite correspond to the Operator === (JavaScript), but it can be useful.


Answer 3

What exactly is it confused? In python True = 1 , and false = 0 . If you need to compare the words true and false , then just take them as rows for example 0 == "false"

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions