Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python bitwise operation on condtion statement 'unexpected' behavior

I’m new to python programing. While solving a practice problem and experimenting with bitwise operation, I ran into unexpected output:

index = 0
time = '?'

print(index)
print(index == 1)
print(time[0].isnumeric())
print(index == 1 & time[0].isnumeric())
print(index == 1 and time[0].isnumeric())

Output:

0
False
False
True
False

As far as I understand:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • False and False should result in False : Boolean operation
  • False & False should result in False : Bitwise operation

Based on the above understanding when I performed bitwise operation on condition statement I getting the output as ‘True’. When I change to boolean operation, I get the expected output of ‘False’.

Can someone please explain this behavior, I’m sure that I’m missing something.
Thanks.

>Solution :

Bitwise operations have similar precedence to other mathematical operations. Just as you would want 1 + 2 == 3 to be interpreted as (1 + 2) == 3 rather than 1 + (2 == 3),

index == 1 & time[0].isnumeric()

is interpreted as

index == (1 & time[0].isnumeric())

i.e.

0 == (1 & False)

In Python, False == 0 and 1 == True, so 1 & False == 1 & 0 == 0.

On the other hand,

index == 1 and time[0].isnumeric()

is interpreted as

(index == 1) and time[0].isnumeric()

just as you would want a == b and c == d to be interpreted as (a == b) and (c == d) rather than a == (b and c) == d.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading