Py学习  »  Python

语法“exp1<<variable<<exp2”在Python中是如何工作的?

Fajela Tajkiya • 3 年前 • 1281 次点击  

当我在看书的时候,我发现了这个例子。

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

我从没见过语法 0 <= price <= product['price'] 之前,很明显,这是在测试价格,应该 >= 0 <= product['price'] .我测试了这个功能,它按预期工作。我想对语法做更多的测试 0<=价格<=产品[价格] .

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')

它总是打印出来 a is not greater than or equal to 0 and less than or equal to 10 .为什么会这样?到底是什么 0 << a << 10 工作

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130393
 
1281 次点击  
文章 [ 3 ]  |  最新文章 3 年前
BrokenBenchmark
Reply   •   1 楼
BrokenBenchmark    3 年前

你的支票使用位移位, 比较操作。它总是会产生一个 falsey 价值

<< 是吗 left shift operator 是的 比较操作(使用 < <= 如果你想要比较)。

为了了解这个表达式是如何工作的,我们从左到右计算运算。所以 0 << a << 10 相当于 (0 << a) << 10 .

  • (0 << a) 0移位了吗 a 位,也就是0。 A. 这里正好是7,但将0移位任意位数仍然会产生0。
  • 0 << 10 在10位上移位0,这仍然是0。
  • 零是一个错误的值,所以 if 检查失败,并且 else 分支被执行。
Rayan Hatout
Reply   •   2 楼
Rayan Hatout    3 年前

<< 是对应于左移位的位运算。左移类似于乘以2。

例如:

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

一般来说 n << m 将等于 n * (2 ** m) .

现在,移位具有从左到右的关联性,因此您的条件将被解释为 ((0 << a) << 10) .使用上面的公式,你会注意到这总是会给我们 0 ,无论 a 0 等价于布尔值 False 所以你的情况永远是这样 错误的

RedWheelbarrow
Reply   •   3 楼
RedWheelbarrow    3 年前

<< 是一个轮班操作员,你需要使用 < <= :

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')