-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
  • 6,699
  • 10
  • 24
  • 37

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
  • 39,199
  • 27
  • 87
  • 126
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
  • 52,115
  • 13
  • 74
  • 94
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
  • 1,901
  • 2
  • 8
  • 17