初学 Python,有个 if 语句一直不执行,后来发现问题出在这,越想越不对劲

2015-02-09 06:19:09 +08:00
 Yvette

首先想到是不是把and& 的用混了,可是查到一个解释说:
and tests whether both expressions are logically True while & (when used with True/False values) tests if both are True.
但是110<122110>97明明都是True啊
而且为什么把第一个110换成100就是正常的。
我觉得是不是我的Python有问题……

8452 次点击
所在节点    Python
14 条回复
imlonghao
2015-02-09 06:24:55 +08:00
运算的顺序可能并不是我们所认为的

先比较两边,然后再比较中间

>>> 110<122 & 110>97
False
>>> (110<122) & (110>97)
True
Valyrian
2015-02-09 06:26:44 +08:00
& = bitwise and, like '&' in C
and = logical and, like '&&' in C
imlonghao
2015-02-09 06:36:12 +08:00
and is a logical operator which is used to compare two values, IE:

> 2 > 1 and 2 > 3
True

& is a bitwise operator that is used to perform a bitwise AND operation:

> 255 & 1
1

http://stackoverflow.com/questions/16696065/is-there-a-difference-between-and-and-with-respect-to-python-sets/16696134#16696134
liubiantao
2015-02-09 06:39:31 +08:00
没学过 Python ,我刚才查了一下文档,又试验了一下,猜测如下。

& 是按位与的意思。

>>> 122 & 110
106

所以 100<122 & 110>97 相当于 100<106>97,显然是 True
而 110<122 & 110>97 相当于  110<106>97,显然是 False

>>> (110<122) & (110>97)
True

加上括号为什么对呢,引用你查到的解释。
and tests whether both expressions are logically True while & (when used with True/False values) tests if both are True.
注意while & (when used with True/False values),也就是说只有当两边都是布尔值的时候,& 才起到 and 的作用,否则 & 优先是按位与的意思。

不准确之处欢迎之处。
yyfearth
2015-02-09 06:50:24 +08:00
一般来说都是位运算的优先级比较高
laoyuan
2015-02-09 07:36:22 +08:00
用 && 就没这事了,&& == and
Tink
2015-02-09 07:38:04 +08:00
带括号,一般为了防止运算顺序错误都会习惯性带括号
cassyfar
2015-02-09 08:00:48 +08:00
一个是logic operation 一个是bit operation
Delbert
2015-02-09 08:12:41 +08:00
@liubiantao “所以 100<122 & 110>97 相当于 100<106>97,显然是 True
而 110<122 & 110>97 相当于 110<106>97,显然是 False”……
写错了吧?
lebowskis
2015-02-09 09:21:48 +08:00
楼主犯了两个错误,一个是对符号理解的错误,&不等同于and,&是按位与的意思,其次,&的优先级比<>高,所以你用&之后的表达式是:110 < (122 & 110) > 97
110 = 0x6e = 0b01101110
122 = 0x70 = 0b01111010
97 = 0x61 = 0b01100001
(122 & 110) = 0b01101010 = 0x6a = 106

即是你的表达式等价于 110<106>97,明显为False
而100<122 & 110>97等价于 100 <106 >97,明显为True
你的python没任何问题。
Osake
2015-02-09 09:30:09 +08:00
乡亲们回答的好 赞一个
linuxzpf
2015-02-09 09:35:59 +08:00
LZ要区分一下 “按位与”和“逻辑与”是不一样的哦。
heaton_nobu
2015-02-09 09:45:51 +08:00
&&
hfli
2015-02-09 10:09:56 +08:00
楼主其实不是把and和&搞混了,而是把"&"和"&&"搞混了 :-)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/169402

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX