Why does this code print "not equals" instead of throwing a TypeError?
int_num = 1
str_num = "2"
if str_num == int_num:
print("equal")
else:
print("not equal")
Why does this code print "not equals" instead of throwing a TypeError?
int_num = 1
str_num = "2"
if str_num == int_num:
print("equal")
else:
print("not equal")
From the current Python documentation for Comparisons:
Objects of different types, except different numeric types, never compare equal. The
==
operator is always defined...
(Emphasis mine.)
How comparisons are defined for standard types:
Objects of different types, except different numeric types, never compare equal. The
==
operator is always defined but for some object types (for example, class objects) is equivalent tois
. The<
,<=
,>
and>=
operators are only defined where they make sense; for example, they raise aTypeError
exception when one of the arguments is a complex number.Non-identical instances of a class normally compare as non-equal unless the class defines the
__eq__()
method.
Equality would work on any objects though:
By default, object implements
__eq__()
by usingis
, returningNotImplemented
in the case of a false comparison:True if x is y else NotImplemented
.