+ 3

Please explain this code:

https://code.sololearn.com/cz6jP4XEwnKI/?ref=app According to what i understand, pi will first evaluate _s3 == s2_, which clearly is _True_, but then it evaluates _s1 is True_ and gives result as _True_ when it should be _False_!?

20th Nov 2019, 9:17 AM
Anirudh Sharma
Anirudh Sharma - avatar
5 Antworten
+ 7
s1 = 'abc' s2 = input() # enter abc s3 = 'abc' print(s1 is s3 == s2) # This reads as <s1> is <s3> AND <s3> == <s2> # <s1> is <s3> checks for reference equality -> True # <s3> == <s2> checks for content equality -> True print(s3 == s2) # <s3> == <s2> checks for content equality -> True print(s1 is True) # checks for reference equality -> False # To verify <s1> and <s3> refers to # same object you can check their ID #print(id(s1), id(s2), id(s3)) Hth, cmiiw
20th Nov 2019, 9:42 AM
Ipang
+ 2
Thanks a lot for explaining Ipang. If there is an _AND_ in between this makes it a lot simpler. But why is there an _AND_ there? Why wouldn't python just evaluate the equality and then the identity? And what is Hth, cmiiw?
20th Nov 2019, 3:38 PM
Anirudh Sharma
Anirudh Sharma - avatar
+ 1
Anirudh Sharma Actually I didn't understand either, in the first place. Then I remember Python allows compound comparison like `a < b < c` which is evaluated (as you probably know already) as `a < b AND b < c`. Then It came to me the evaluation of `s1 is s3 == s2` looks pretty much the same. And turned out it makes just the sense : ) "Why wouldn't Python just evaluate the equality and then identity?" I don't have the answer to that question apparently. Hope That Helps, Correct Me If I'm Wrong => Hth, cmiiw
20th Nov 2019, 3:48 PM
Ipang
+ 1
Ipang, you are awesome, your explanation is perfect. This issue was troubling me for days, i thought py was useless as it would develop similar issues in bigger formulae; instead it turn out to be better in terms of compound comparison!! Tal,thal
20th Nov 2019, 3:53 PM
Anirudh Sharma
Anirudh Sharma - avatar
+ 1
You're welcome, I'm glad if it helps : )
20th Nov 2019, 4:13 PM
Ipang