Thursday, March 23, 2023
HomePythonBizarre Comparability Situation in Python

Bizarre Comparability Situation in Python


Hello guys! I’m again with a brand new article. This time I’ll sort out an issue which appears simple sufficient at first however will surprize a few of you. Suppose you may have the next piece of code:

a = 3
b = False
c = """12"""
d = 4.7

and you need to consider this:

d + 2 * a > int(c) == b

Earlier than studying the remainder of the submit please take a minute to resolve this assertion in your head and attempt to provide you with the reply.

So whereas fixing it my thought course of went one thing like this:

2 * a = 6
d + 6 = 10.7
10.7 > int(c) is the same as False
False == b is the same as True 

However lo-and-behold. If we run this code in Python shell we get the next output:

False

Dang! What went improper there? Was our pondering improper? I’m fairly positive it was imagined to return True. I went via the official docs a few instances however couldn’t discover the reply. There was additionally a chance in my thoughts that this may be some Python 2 bug however once I tried this code in Python 3 I acquired the identical output. Lastly, I turned to the Python’s IRC channel which is all the time filled with extraordinarily useful folks. I acquired my reply from there.

So I acquired to know that I used to be chaining comparisons. However I knew that already. What I didn’t know was that everytime you chain comparisons, Python compares every factor so as after which does an “AND”. So our comparability code is equal to:

(d + 2*a) > (int(c)) and (int(c)) == (b)

This brings us to the query that everytime you chain comparisons, does Python compares every factor so as after which does an “AND”?

Because it seems that is precisely what Python does: x <comparability> y <comparability> z is executed identical to x <comparability> y and y <comparability> z, besides y is simply evaluated as soon as.

I hope you discovered this text useful. When you’ve got any questions, feedback, strategies please be happy to achieve out to me through electronic mail or the feedback part under.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments