Thursday 16 May 2019

boolean - Using IF, AND, OR together with EQUAL operand together in Python

It helps to examine the logic of this line:




if (len(x) == (4 or 6)):


The (4 or 6) clause contains a logical or short circuit. The value 4 is true, so it is evaluated and returned to the == relational comparison.



The way that or works is that its lefthand side is evaluated for Boolean truth, and its value is returned if true. If the lefthand side is not Boolean true, then the righthand side is evaluated and its value is returned.



Because the lefthand side of the 4 or ... is true in a Boolean sense, the righthand side is never evaluated. Python doesn't even look past 4 or. If the left-hand value were a false value (such as 0), then the right hand side of the or would be evaluated.



To see this in action, try print 4 or 6. The output will be 4.




So since the 4 is a hard-coded true value, your comparison is semantically the same as if (len(x) == 4) -- that is, since 4 is true, 6 is never evaluated.



What I suppose you really want to know is if len(x) is either 4 or 6. You could put that to code in a couple of ways:



if(len(x) == 4 or len(x) == 6 ...

if(len(x) in (4,6) ...

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...