2

While I was reading a book, I found this example.

def apply_discount(product, discount):
    price = int(product['price'] * (1.0 - discount))
    assert 0 <= price <= product['price']
    return price

I never saw the syntax 0 <= price <= product['price'] before, and it's clear that here it's testing the price, which should >= 0 and <= product['price']. I tested the function and it works as expected. I want to do more testing about the syntax 0 <= price <= product['price'].

a = 7
if 0 << a << 10:
    print('a is greater than or equal to 0 and less than or equal to 10')
else:
    print('a is not greater than or equal to 0 and less than or equal to 10')

It always prints a is not greater than or equal to 0 and less than or equal to 10. Why does it happen? What exactly does 0 << a << 10 work?

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Fajela Tajkiya
  • 629
  • 2
  • 10

3 Answers3

2

<< is a shift operator, you need to use < or <=:

a = 7
if 0 <= a <= 10:
    print('a is greater than or equal to 0 and less than or equal to 10')
else:
    print('a is not greater than or equal to 0 and less than or equal to 10')
Alain Bianchini
  • 3,883
  • 1
  • 7
  • 27
2

<< is a bitwise operation that correspond to a left shift. A left shift is analogous to multiplying by two.

For example:

print(2 << 1)
# 4
print(2 << 2) # Do two left-shifts
# 8

In general, n << m will be equal to n * (2 ** m).

Now shifting has a left to right associativity so your condition will be interpreted as ((0 << a) << 10). Using the formula above, you'll notice that this will always give us 0, regardless of what the value of a is. 0 is equivalent to a boolean False so your condition will always be False

Rayan Hatout
  • 640
  • 5
  • 22
1

Your check uses bit-shifting, not comparison operations. It will always produce a falsey value.

<< is the left shift operator. It is not a comparison operation (use < or <= if you want comparison).

To see how this expression works, we evaluate the operations left to right. So, 0 << a << 10 is equivalent to (0 << a) << 10.

  • (0 << a) is 0 shifted over a bits, which is 0. a happens to be 7 here, but shifting 0 over by any number of bits would still produce zero.
  • 0 << 10 is 0 shifted over 10 bits, which is still 0.
  • Zero is a falsey value, so the if check fails, and the else branch is executed.
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33