0

Below are the different scenarios tried using '&' and 'and' conditional operators and its result. (using Python 2.7)

  1. Using '&' operator:

enter image description here

  1. Using 'and' operator:

enter image description here

Wondering why both conditional operators showing different behaviour? Explanation with real scenarios would be helpful.

Thanks in advance.

3

4 Answers 4

5

& is not a conditional operator. It stands for the bitwise and. Not only it is a different operator but also the operator precedence is different (and is below > while & is above).

So first of all an example:

>>> 1 and 2
2
>>> 1 & 2
0

Now lets analyze your case:

>>> point = 1
>>> score = 2
>>> point == 1 & score > 0

Now the operator precedence kicks in and the last line is equivalent to

>>> point == (1 & score) > 0

Note that == and > have equivalent precedence. So lets evaluate that:

>>> 1 & score
0
>>> point == 0 > 0

The last line is equivalent to (point == 0) > 0 (when operators have equal precedence then you simply go from left to right). Lets evaulate that:

>>> point == 0
False
>>> False > 0
False

All in all

>>> point == 1 & score > 0
False

Can you break down the evaluation for your second statement now?

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please elaborate the answer. if we do like (point == 1 & (score > 0)) => return true.
@PrashantkumarKB I've updated the answer. I'm not sure what you are trying to do but unless you are going to manipulate bits then don't use &.
1

The issue is that & is not actually a logical "and", it's a bitwise operator. So it'll compare two numbers by each bit, and produce a number that has a bit set if both of the first two numbers had that bit set. So 1 & 2 will give you 0.

This wouldn't usually be a problem (True is 1, False is 0) - except that the operator precedence for & and and relative to > and = are different.

So 1 == 1 & 2 > 0 (the first case):

  • This is interpreted as 1 == (1 & 2) > 0, or 1 == 0 > 0, and since 1 == 0 is False the whole thing is False.

Whereas 1 == 1 and 2 > 0 (the second case):

  • This is interpreted as (1 == 1) and (2 > 0), and since both of those cases are True, the whole thing is True.

1 Comment

You're absolutely right, and I've corrected my answer.
0

and tests whether both expressions are logically True while & (when used with True/False values) tests if both are True.

1 Comment

>>> point = 1 >>> score = 2 >>> point == 1 True >>> score > 0 True
0

& is a bitwise AND operator, whereas and is a logical operator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.