Reputation: 1
Can you give the clarity in Python
i = 2
if i<3 and i>1:
print('its ok')
Output: 'its ok' ------> no problem over here
But when I'm going to use Bitwise AND instead of AND, the code has been executed but nothing in output.
i = 2
if i<3 & i>1:
print('its ok')
Output: nothing ------> why ??
Upvotes: 0
Views: 50
Reputation: 470
i<3 & 1>1
is read as i<(3 & i)>1
.
&
is the bitwise AND operator.
So, this evaluates to i<(3 & 2)>1
which is equal to i<2>1
.
i
( = 2) is not less than 2, so the first condition is False
. Therefore, it fails the condition.
Upvotes: 0
Reputation: 797
Bitwise operate on numbers, but they treat them as if they were a string of bits, written in binary.
a & b
The &
operator returns 1 when the corresponding bits of both a and b are 1. Otherwise it returns 0.
If you use the && logical operator, it will work as you want it:
i = 2
if i < 3 && i > 1:
print('Works!')
Upvotes: 0
Reputation: 1057
You are trying to use bitwise AND (&) to perform logical AND (&&) operation!
It should be
if i<3 && i>1:
print('its ok')
Upvotes: 2