目录
python从小白到总裁完整教程目录:https://blog.csdn.net/weixin_67859959/article/details/129328397?spm=1001.2014.3001.5502
❤ 逻辑运算符
优先级:() > not > and > or
逻辑运算符 可以连接多个条件, 在判断和循环中使用
1. and
and - 逻辑与 - 和 - 并且 and连接两个条件,都必须为 True, 整体结果才为 True, 即一假为假 (当第一个条件为 False 的时候,第二个条件就不再判断)
逻辑运算符and,x and y,如果x为True则返回y值。如果x为False则返回y值。如果x的值为True,and的运算不会结束,会继续看y的值,所以此时真与假取决于y的值,所以x如果为真,则返回y的值。如果x为假,那么and运算就会结束运算过程了,因为有一个为假则and为假,所以返回x的值。
x = -100
y = -500
print(x < 0 and y < 0) # True
print(x < 0 and y > 0) # False
print(x < 0 and 1/2) # 0.5 ***
print(x > 0 and 1/2) # False 短路
print(1 and 2) # 2
print(3 and 0) # 0
print(0 and 2) # 0
print(3 and 2) # 2
print(0 and 0) # 0
说明:1为True,0为False
2. or
or - 逻辑或 - 或者 or连接的两个条件, 只要有一个条件为 True , 整体结果就为 True, 即 一真为真 (当第一个条件为 True的时候,第二个条件就不再判断)
逻辑运算符or,x or y, 如果x为True则返回x,如果x为False返回y值。因为如果x为True那么or运算就不需要在运算了,因为一个为真则为真,所以返回x的值。如果x的值为假,那么or运算的结果取决于y,所以返回y的值。
x = -100
y = -500
print(x > 0 or y < 0) # True
print(x > 0 or y > 0) # False
print(x < 0 or 1/2) # True 短路
print(1 or 2) # 1
print(3 or 2) # 3
print(0 or 2) # 2
print(0 or 100) # 100
print(0 or 0) # 0
3. not
not 逻辑非 取反 not后边的条件, 如果本来是 True,变为 False, 本来是 False,变为 True
x = -100
y = -500
print(not x > 0) # True
❤ 混合例子与解析
print(1 > 2 and 3 or 4 and 3 < 2 or not 4 > 5)
按照从左向由,优先级高的先执行优先级高的规则,首先因为比较运算符优先级高于逻辑运算符,很简单,如果运算符低于了逻辑运算符优先级那还如何运算呢。and 优先级大于 or,not优先级大于and和or
not 4 > 5 为True
1 > 2 为 False
3 < 2 为 False
Flase and 3,因为False为假所以and不在运算直接返回False
4 and False,因为4为真所以and运算符会继续运算后面的,以False为主,所以返回False。
False or False,为False
False or True,为True
False or False,因为False为假,所以or运算符会继续运算后面的,以False为主,所以返回后面的False值