Reputation: 6486
I am trying to compare if two different variables lie in two different ranges in Python using the logical operator '&' and the relational operator 'if'. The question might be a silly one and I am sure it will be down voted but even then why doesn't this code work?
Code
a = 2.0
b = 3.0
if 1 <= a <= 4 & 2 <= b <= 5:
print 'Yes'
if 1 <= a <= 4:
print 'Yes, a'
if 2 <= b <= 5:
print 'Yes, b'
Output
Yes, a
Yes, b
And what is the best method to do such comparisons?
Upvotes: 0
Views: 768
Reputation: 13869
and
is boolean AND. &
is bitwise AND.
Because bitwise AND has higher precedence (i.e. it is more binding) than the <=
operator, it gets evaluated first when you don't wrap the left and right boolean comparison expressions in parentheses.
So the evaluation is like:
1 <= a <= 4 & 2 <= b <= 5
1 <= 2.0 <= (4 & 2) <= 3.0 <= 5
1 <= 2.0 <= 0 <= 3.0 <= 5
Which is obviously False
. What you want is:
1 <= a <= 4 and 2 <= b <= 5
And you don't need parentheses here because theand
operator has lower precedence than <=
so the left and right expressions will get evaluated first by default.
It's worth taking a look at the operator precedence table. You don't need to memorize it, but it's good for understanding all the Python operators and their general relationship to one another.
Upvotes: 3
Reputation: 177
&
is a bitwise operator.Use and instead of &.
if 1 <= a <= 4 and 2 <= b <= 5:
print 'Yes'
Upvotes: 0
Reputation: 74645
Consider:
>>> a = 2.0
>>> b = 3.0
>>>
>>> if 1 <= a <= 4 & 2 <= b <= 5:
... print 'Yes'
...
>>> if 1 <= a <= 4 and 2 <= b <= 5:
... print 'Yes'
...
Yes
Upvotes: 1
Reputation: 303
Note that &
is a bitwise operator instead of a logical operator.
In python, logic operators consist of keyword and
, or
and not
. In your case:
if 1 <= a <= 4 and 2 <= b <= 5:
print 'Yes'
Upvotes: 0