“and"的python条件运算符中的奇怪行为和“&" [英] weird behaviour in python conditional operators for "and" and "&"
问题描述
以下是尝试使用&"的不同场景和 'and' 条件运算符及其结果.(使用 Python 2.7)
- 使用&"操作员:
- 使用和"运算符:
想知道为什么两个条件运算符都表现出不同的行为?用真实场景进行解释会很有帮助.
提前致谢.
&
不是条件运算符.它代表按位和.它不仅是一个不同的运算符,而且是 运算符优先级是不同的(and
在 >>
下面,而 &
在上面).
首先举个例子:
<预><代码>>>>1 和 22>>>1 &20现在让我们分析您的案例:
<预><代码>>>>点 = 1>>>分数 = 2>>>点 == 1 &得分 >0现在运算符优先级生效,最后一行相当于
<预><代码>>>>点 == (1 & 分数) >0请注意,==
和 >
具有相同的优先级.所以让我们评估一下:
最后一行相当于 (point == 0) >0
(当运算符具有相同的优先级时,您只需从左到右即可).让我们评估一下:
总而言之
<预><代码>>>>点 == 1 &得分 >0错误的你现在能分解你的第二个陈述的评价吗?
Below are the different scenarios tried using '&' and 'and' conditional operators and its result. (using Python 2.7)
- Using '&' operator:
- Using 'and' operator:
Wondering why both conditional operators showing different behaviour? Explanation with real scenarios would be helpful.
Thanks in advance.
&
is not a conditional operator. It stands for the bitwise and. Not only it is a different operator but also the operator precedence is different (and
is below >
while &
is above).
So first of all an example:
>>> 1 and 2
2
>>> 1 & 2
0
Now lets analyze your case:
>>> point = 1
>>> score = 2
>>> point == 1 & score > 0
Now the operator precedence kicks in and the last line is equivalent to
>>> point == (1 & score) > 0
Note that ==
and >
have equivalent precedence. So lets evaluate that:
>>> 1 & score
0
>>> point == 0 > 0
The last line is equivalent to (point == 0) > 0
(when operators have equal precedence then you simply go from left to right). Lets evaulate that:
>>> point == 0
False
>>> False > 0
False
All in all
>>> point == 1 & score > 0
False
Can you break down the evaluation for your second statement now?
这篇关于“and"的python条件运算符中的奇怪行为和“&"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!