语法“exp1 << variable << exp2”在 Python 中是如何工作的? [关闭]
python 196
原文标题 :How does the syntax “exp1 << variable << exp2" work in Python? [closed]
我在看书的时候发现了这个例子。
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 <= 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')
它总是打印a is not greater than or equal to 0 and less than or equal to 10
。为什么会这样? 0 << a << 10
具体有什么作用?
回复
我来回复-
RedWheelbarrow 评论
该回答已被采纳!
<<
是移位运算符,需要使用<
或<=
: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')
2年前 -
Rayan Hatout 评论
<<
是对应于左移的按位运算。左移类似于乘以 2。例如:
print(2 << 1) # 4 print(2 << 2) # Do two left-shifts # 8
一般来说,
n << m
等于n * (2 ** m)
。现在移位具有从左到右的关联性,因此您的条件将被解释为
((0 << a) << 10)
。使用上面的公式,您会注意到无论a
的值是什么,它总是给我们0
。0
等价于布尔值False
所以你的条件将永远是False
2年前 -
BrokenBenchmark 评论
您的检查使用位移,而不是比较操作。它总是会产生一个错误的值。
<<
是左移运算符。它不是比较操作(如果要比较,请使用<
或<=
)。为了了解这个表达式是如何工作的,我们从左到右评估操作。所以,
0 << a << 10
等价于(0 << a) << 10
。- (0 << a) 是 0 在 a 位上移位,即 0。a 在这里恰好是 7,但是将 0 移位任意位数仍然会产生零。
- 0 << 10 是 0 移位了 10 位,仍然是 0。
- 零是一个错误值,因此 if 检查失败,并执行 else 分支。
2年前