Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does the syntax "exp1 << variable << exp2" work in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

<< 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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading