I know python2.7 allows comparison between different types. So the equality comparison between str and int will result in False
. Can the comparison ever be true depending on the values of a and b?
a = input('we input some string value a')
if (a==int('some string b')):
print("yes")
else:
print("no, never!!")
Can this above snippet ever output "yes"? If yes, when?
CodePudding user response:
Short answer: Yes, this can produce yes
as an answer (assuming 'some string b'
is a placeholder for a string that might actually contain a legal int
representation; if it's that exact literal string, you'd just get a ValueError
when you called int
on it).
Long answer:
An
int
and astr
will never compare equal.int
andstr
are unrelated different types, and while there is a tiny amount of type flexibility (different numeric types are comparable the way they are in most languages), even on Python 2 (where<
/>
/<=
/>=
don't raise exceptions and use a ridiculous fallback comparison to provide an arbitrary ordering of unrelated types) it's a strongly typed language andint
andstr
do not interoperate like that.That said,
input
on Python 2 is terrible; iteval
s the text received from the user, so if the user enters12345
, it will in fact return anint
. So if the user input a legalint
literal, and'some string b'
was itself a legal representation of anint
, then you'd've provided a realint
to compare to on both sides, and this code could returnyes
, not becausestr
andint
compare equal to one another, but becauseinput
will returnint
s when the input looks like anint
(andfloat
s forfloat
-looking things).
Side-note: In pathological cases, someone could have name-shadowed the input
and/or int
built-ins on a prior line, and anything could happen. I'm not going to get into the details there; it's a programming language, you're allowed to do stupid things with it, but there's nothing interesting about telling it to do stupid things and wondering if it will be stupid.
CodePudding user response:
if a string value eg: 23456 to an integer eg: 32143 you might get a result. Comparing 1234 to defg has no purpose.