-2

Why does option a) prints x, while on b) it doesn't? By the way, both operations should bring the result of b).

a)

x = 7

if x >3 & x<=6:
    print(x)

b)

x = 7

if x >3:
    if x<=6:
        print(x)
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39

3 Answers3

4

The ampersand (&) character is a bitwise operator. From the Python Wiki page on Bitwise operators:

x & y

   Does a "bitwise and". Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0.

If you evaluate your expression x >3 & x<=6, the result is:

x >3 & x<=6
7 > 3 <= 6
True <= 6
True

... which is why your code reaches the final condition and outputs 7.


What you're looking for is the logical and token:

x = 7

if x >3 and x<=6:
    print(x)
esqew
  • 42,425
  • 27
  • 92
  • 132
  • @RobertoCaboni Updated to reflect this aspect of the question, thanks – esqew Jul 07 '20 at 20:09
  • 2
    `x >3 & x<=6` is not parsed as `1 & 1`, as `&` has a higher priority than `<`. See @khelwood's answer for the correct explanation. – Thierry Lathuille Jul 07 '20 at 20:12
  • @ThierryLathuille Ah yes... seems I totally missed this point in my haste to answer! I've updated to reflect the correct logic - thanks! – esqew Jul 07 '20 at 20:16
4

This condition:

if x >3 & x<=6

is checking if x > (3&x) and (3&x) <= 6.

x is 7, so 3&x is equal to 3. So both conditions are true.


In general, if you want to check if two conditions are both true, use and.

if x > 3 and x <= 6:

For what you want in this case, you can do it more concisely:

if 3 < x <= 6:
khelwood
  • 55,782
  • 14
  • 81
  • 108
1

With the first, you are using the bitwise operator for and, instead of and which correctly would not print x in the case of 7.

duckboycool
  • 2,425
  • 2
  • 8
  • 23