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:
False and Falseshould result inFalse: Boolean operationFalse & Falseshould result inFalse: 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.