Python的布尔操作

2019年11月20日 / 223次阅读 / Last Modified 2019年11月20日
语法

含有and,or,not关键词的python表达式,就叫做布尔操作。布尔操作的结果,不一定是True或False。

如下是布尔操作的规则:

  • x or y,如果x的真值判断是False,就返回y,否则返回x;
  • x and y,如果x的真值判断是False,就返回x,否则返回y;
  • not x,如果x的真值判断是False,就返回True,否则返回False。

关于python的真值判断!

三条规则,其实只有最后一条,返回的是True或False,前面两个都是返回的x或y对象。这前面两条规则,也被成为短路操作符,short-circuit operator。可以使用短路操作符来做赋值,请参考:python带条件判断的赋值语句

注意,布尔操作不等同于布尔判断!我们使用 ==,<=,>,...这些操作,实在做布尔判断,布尔判断的结果一定是True或False。

只有not这个布尔操作的返回值与布尔判断一致,不过,not这个布尔操作符的优先级比较低,比如 not a == b,就是 not (a == b)。要先判断a == b,然后再取反。因此,这样写就不对了: a == not b,一定要用括号括起来: a == (not b)。

-- EOF --

本文链接:https://www.pynote.net/archives/1532

留言区

《Python的布尔操作》有1条留言

您的电子邮箱地址不会被公开。 必填项已用*标注

  • 麦新杰

    The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument. [回复]


前一篇:
后一篇:

More

麦新杰的Python笔记

Ctrl+D 收藏本页


©Copyright 麦新杰 Since 2019 Python笔记

go to top