0

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?

1 Answer 1

1

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:

  1. An int and a str will never compare equal. int and str 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 and int and str do not interoperate like that.

  2. That said, input on Python 2 is terrible; it evals the text received from the user, so if the user enters 12345, it will in fact return an int. So if the user input a legal int literal, and 'some string b' was itself a legal representation of an int, then you'd've provided a real int to compare to on both sides, and this code could return yes, not because str and int compare equal to one another, but because input will return ints when the input looks like an int (and floats for float-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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.