查看原文
其他

python3基础05布尔类型和比较运算符

pythonic生物人 pythonic生物人 2022-09-11

"pythonic生物人"的第40篇分享


原创不易,点个“赞“或"在看"鼓励下呗

摘要

本文梳理python中布尔运算和比较运算符使用。

目录

1、布尔类型布尔类型简介布尔运算2、比较运算比较运算简介比较运算符连续比较
正文开始啦

1、布尔类型

布尔类型简介

  • python中布尔类型有两种,真True和假False,True和False等价于数值1和0,可以直接参与运算;
In [20]: True + 2
Out[20]: 3

In [21]: False + 2
Out[21]: 2
  • True和Fasle用于控制结构中决定程序继续执行还是中断;
  • bool函数用于判断一个对象是真还是假,一个python对象要么是True要么是Fasle;
  • python视为假的内置对象如下:
  1. 常量: None 和 False。
  2. 数值类型的零: 0, 0.0, 复数中0j, 四舍五入中Decimal(0), 分数中Fraction(0, 1)
  3. 空的序列和多项集: '', (), [], {}, 空集合set(), range(0)
In [15]: bool(0j)
Out[15]: False

In [16]: bool(1)
Out[16]: True

In [17]: bool(0)
Out[17]: False

In [18]: bool(None)
Out[18]: False

In [19]: bool(False)
Out[19]: False

布尔运算

布尔运算结果常作为控制结构(if while)的条件,用于判断程序中断还是继续执行;三个布尔运算符:and(且),or(或),not(否)。

  • a and b:a和b均为真,返回真。短路运算符,如果a为假,不会再判断b;如果a为真再判断b。
  • a or b:a和b有一个为真,返回真。短路运算符,如果a为假再判断b;如果a为真,不会判断b。
  • not a:取a真或假的反面;not运算符优先级低,not a == b 等价于 not (a == b)。
In [51]: 1 and 2#and为短路运算,1为真,再检测2也为真,整个表达式输出2,即为真
Out[51]: 2

In [52]: [] and 2#[]为假,表达式短路,输出[]
Out[52]: []

In [53]: [] or 2#[]为假,在检测[]
Out[53]: 2

2、比较运算

比较运算简介

返回True或者Fasle;

In [30]: 1 < 2
Out[30]: True

In [31]: 1 == 2
Out[31]: False

不同类型的对象不能比较,强行比较会报错。

In [32]: 1 < "x"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-055a687f025c> in <module>
----> 1 1 < "x"

TypeError: '<' not supported between instances of 'int' and 'str'

比较运算符

各个比较运算符优先级相同,但是比布尔运算符的优先级高。

比较运算符   含义
小于    <
小于等于   <=
等于    ==
不等于       !=
大于    >
大于等于   >=
对象标识   is
否定的对象标识     is not

实例

In [40]: 1 is 2
Out[40]: False

In [41]: 1 is 1
Out[41]: True

In [42]: 1 == 2
Out[42]: False

In [43]: 1 == 1
Out[43]: True

In [44]: 1 is not 2
Out[44]: True

In [45]: 1 != 2
Out[45]: True

In [46]: "a" is "b"
Out[46]: False

In [47]: "a" is not "b"
Out[47]: True

In [50]: [1, 2, 1] < [1, 3, 0]#两个列表比较,从左到右一个一个比较。
Out[50]: True

连续比较

a < b < c,等价于a < b and b < c。

In [48]: 1 < 0 < 3#等价于1 < 0 and 0 < 3
Out[48]: False

参考资料

https://docs.python.org/zh-cn/3.7/library/stdtypes.html#boolean-operations-and-or-not

同系列文章


python3基础01数值和字符串(一)
python3基础02数值和字符串(二)
python3基础03列表(list)和元组(tuple)
python3基础04字典(dict)和集合(set)


原创不易"点赞"、"在看"鼓励下呗


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存