P11 布尔类型 + P12

P11 布尔类型

(一)bool()函数

只有空字符串或等值于零的结果才是False

>>> bool(" ")
True
>>> bool("")
False
>>> bool("False")
True
>>> bool(False)
False
>>> bool(520)
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0j)
False

【笔记】结果为False的所有情况:

1.定义为False的对象:None , False
2.值为0的数字类型:0 , 0.0 , 0j , Decimal(0) , Fraction(0,1)
3.空的序列和集合:'' , () , [] , set() , range()

【应用】条件语句

>>> if 520 > 250:
	print("520比250大")
else:
	print("520不比250大")

	
520比250大
>>> if bool(250):
	print("250 is True")
else:
	print("250 is False")

	
250 is True

【拓展】布尔类型其实就是特殊的整数类型

>>> 1 == True
True
>>> 0 == False
True
>>> True + False
1
>>> True - False
1
>>> True * False
0
>>> True / False
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    True / False
ZeroDivisionError: division by zero


 (二)逻辑运算符(也较布尔运算)

示例: 

>>> 3 < 4 and 4 < 5
True
>>> 3 < 4 and 4 > 5
False
>>> 3 < 4 or 4 > 5
True
>>> not True
False
>>> not False
True
>>> not 250
False
>>> not 0
True

 任何对象可以直接进行真值测试


【问题延伸】为什么会出现上面+下面的情况?

>>> (not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)
4

【答案】因为 and or 运算,遵从短路逻辑



P12 短路逻辑和运算符优先级

(一)短路逻辑

        短路逻辑的核心思想:从左往右,只有当第一个操作数的值无法确定逻辑运算的结果时,才对第二个操作数进行求值。

>>> 3 and 4
4
>>> 4 or 5
4
>>> 0 and 3
0
>>> 0 or 3
3

 (二)运算符优先级

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值