python第十三章:数据类型之布尔

发布时间 2023-11-17 08:23:45作者: 刘宏缔的架构森林

一,什么是布尔类型?

bool类型,全称为布尔类型(Boolean),

它的作用:表示逻辑判断的结果,就是真(True)或假(False)这两个值

bool类型的变量只能取两个值: True或False,

True表示真,False表示假。

1
2
3
4
5
6
7
8
9
10
11
12
13
# 用户是否登录
isLogin = True
# 输出:True
print("用户是否登录:", isLogin)
# 输出:<class 'bool'>
print(type(isLogin))
 
# 用户是否激活
isActive = False
# 输出:False
print("用户是否激活:", isActive)
# 输出:<class 'bool'>
print(type(isActive))

运行结果:

用户是否登录: True
<class 'bool'>
用户是否激活: False
<class 'bool'>

二,比较运算符(>,<, == ,!= 等)返回的结果就是布尔类型:

1
2
3
4
5
6
x = 10
isGreater = x > 5
# 输出:False
print("x是否大于5:", isGreater)
# 输出:<class 'bool'>
print(type(isActive))

运行结果:

x是否大于5: True
<class 'bool'>

说明:刘宏缔的架构森林—专注it技术的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/11/14/python-di-shi-san-zhang-shu-ju-lei-xing-zhi-bu-er/
代码: https://github.com/liuhongdi/ 或 https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com

三,布尔值可以用布尔运算符进行运算:

and运算是与运算,只有两个值都为Trueand运算结果才是True,
or运算是或运算,只要其中有一个值为Trueor运算结果就是True
not运算是非运算,它是一个单目运算符,把True变成FalseFalse变成True

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# and运算
print(True and True# True
print(True and False# False
print(False and False# False
print(8 > 3 and 5 > 1# True
print(4 > 7 and 5 > 1# False
 
# or运算
print(True or True# True
print(True or False# True
print(False or False# False
print(8 > 3 or 2 > 5# True
print(4 > 7 or 5 > 9# False
 
# not运算
print(not True# False
print(not False# True
print(not 1 > 3# True
print(not 3 > 1# False

运行结果:

True
False
False
True
False

True
True
False
True
False

False
True
True
False