Python 中关于 and、or的判断顺序问题,什么是二元布尔操作符?

Python 中关于 and、or的判断顺序问题

什么是二元布尔操作符

andor操作符总是接受两个布尔值(或表达式),所以被认为是“二元”操作符;

and操作符真值表

True and True		True
True and False		False
False and True 		False
False and False		False	

or操作符真值表

True or True		True
True or False		True
False or True		True
False or False		False

not操作符

not操作符求值为相反的布尔值

真值表

not True		False
not False		True

混合布尔和比较操作符

(4<5) and (5<6)
True
(4<5) and (9<6)
False
(1==2) or (2==2)
True
2+2 == 4 and not 2+2 == 5 and 2*2 == 2+2
True

操作顺序:先求值not操作符,然后是and操作符,然后是or操作符;

如果一个语句中遇到多个andor的情况下该如何判断执行的顺序呢?

基本逻辑:

  • 有括号的先计算括号内的;

  • 执行顺序:

    • 从前到后开始执行;

    • 执行结果:

      • 如果第一个结果为True后面是or,那么最终结果是True

        a = True
        b = False
        c = False
        if a or b and c:
        	print(123)
        123
        
      • 如果True后面是and,后面继续判断;

        a = True
        b = False
        c = False
        if a and b or c:	# a and b 返回False
        	print(123)		# False or c 返回False
        # 没有输出
        
        a = True
        b = False
        c = True
        if a and b or c:	# a and b 返回False
            print(123)		# False or c 返回True
        123
        
      • 如果False后面是or,继续向后判断;

        a = False
        b = True
        c = False
        if a or b and c:	# a or b 返回True
        	print(123)		# True and c 返回False
        # 没有输出
        
        a = False
        b = True
        c = True
        if a or b and c:	# a or b 返回True
            print(123)		# True and c 返回True
        123
        
      • 如果False后面是and,继续向后判断;

        a = False
        b = True 
        c = True
        if a and b or c:	# a and b 返回False
        	print(123)		# False or c 返回 True
        123
        
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值