Python的与或非和逻辑短路

与或非

>>> print(0 or [1,2,3])
[1, 2, 3]
>>> print(0 and [])
0
>>> print(set() or True)
True
123456
  • 由于python对于对象的布尔判断是基于对象的bool()方法或len()方法的,所以或和与返回的其实是判断对象而不是布尔值!
  • 可以将与或非近似理解为下面的函数:
def BooleanNOT(x):
    # not x
    if x:
        return False
    else:
        return True

def BooleanOR(x, y):
    # x or y
    if not x:
        return y
    else:
        return x

def BooleanAND(x, y):
    # x and y
    if not x:
        return x
    else:
        return y

12345678910111213141516171819202122

逻辑短路

  • 由上一节,可以十分直观地了解到: 在逻辑判断中,并不是每一个判断对象都会被执行.
  • 与运算的第一个对象值为false,则第二个对象会被略过.
  • 或运算的第一个对象值为true,则第二个同样对象会被略过.
  • 这种由于逻辑运算机制而导致的现象就叫做逻辑短路.
>>> def print_but_false():
        print("print but false")
        return False

>>> True or print_but_false()
True
>>> False and print_but_false()
False
>>> print_but_false() and True
print but false
False
>>> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值