Kirill
Kirill

Reputation: 1538

Why in Python 1.0 == 1 >>> True; -2.0 == -2 >>> True and etc.?

I want to make condition than number has to be integer. And x == int(x) doesn't help in cases when x == 1.0... Thank you.

Upvotes: 0

Views: 8679

Answers (4)

F.E.A
F.E.A

Reputation: 151

Python converts the integer value into its real equivalent, then checks the two values, and thus the answer is true when checking value equivalence, but if one is checking type equivalence then the answer is false.

Upvotes: 0

michaelsnowden
michaelsnowden

Reputation: 6202

Not big on python, but I used this to check:

i = 123
f = 123.0

if type(i) == type(f) and i == f:
    print("They're equal by value and type!")      
elif type(i) == type(f):
    print("They're equal by type and not value.")
elif i == f:
    print("They're equal by value and not type.")
else:
    print("They aren't equal by value or type.")

Returns:

They're equal by value and not type.

Upvotes: 5

chyyran
chyyran

Reputation: 2656

Just check if it's an integer.

>>> def int_check(valuechk, valuecmp):
        if valuechk == valuecmp and type(valuechk) == int:
                return True
        else:
                return False

>>> int_check(1, 1)
True
>>> int_check(1.0, 1)
False

Upvotes: 0

user2357112
user2357112

Reputation: 281958

isinstance(x, (int, long))

isinstance tests whether the first argument is an instance of the type or types specified by the second argument. We specify (int, long) to handle cases where Python automatically switches to longs to represent very large numbers, but you can use int if you're sure you want to exclude longs. See the docs for more details.

As for why 1.0 == 1, it's because 1.0 and 1 represent the same number. Python doesn't require that two objects have the same type for them to be considered equal.

Upvotes: 10

Related Questions