“and"的python条件运算符中的奇怪行为和“&" [英] weird behaviour in python conditional operators for "and" and "&"

查看:48
本文介绍了“and"的python条件运算符中的奇怪行为和“&"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是尝试使用&"的不同场景和 'and' 条件运算符及其结果.(使用 Python 2.7)

  1. 使用&"操作员:

  1. 使用和"运算符:

想知道为什么两个条件运算符都表现出不同的行为?用真实场景进行解释会很有帮助.

提前致谢.

解决方案

& 不是条件运算符.它代表按位和.它不仅是一个不同的运算符,而且是 运算符优先级是不同的(and>> 下面,而 & 在上面).

首先举个例子:

<预><代码>>>>1 和 22>>>1 &20

现在让我们分析您的案例:

<预><代码>>>>点 = 1>>>分数 = 2>>>点 == 1 &得分 >0

现在运算符优先级生效,最后一行相当于

<预><代码>>>>点 == (1 & 分数) >0

请注意,==> 具有相同的优先级.所以让我们评估一下:

<预><代码>>>>1 &分数0>>>点 == 0 >0

最后一行相当于 (point == 0) >0(当运算符具有相同的优先级时,您只需从左到右即可).让我们评估一下:

<预><代码>>>>点 == 0错误的>>>错误 >0错误的

总而言之

<预><代码>>>>点 == 1 &得分 >0错误的

你现在能分解你的第二个陈述的评价吗?

Below are the different scenarios tried using '&' and 'and' conditional operators and its result. (using Python 2.7)

  1. Using '&' operator:

  1. 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条件运算符中的奇怪行为和“&amp;"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆