python逻辑运算

1. 与(and)
该操作符有两个操作数,要求这两个操作数都是布尔型的。如果两个操作数都是 True,那么结果是 True;否则就是 False。

表1所示为其运算规则。

表1:与运算规则

ABA and B
True True True
True False False
False True False
False False False


下面是实际操作的情况:

>>> True and True # 两个操作数都是True
True
>>> True and False # 两个操作数一个是True,另外一个是False
False
>>> False and True # 两个操作数一个是True,另外一个是False
False
>>> False and False # 两个操作数都是False
False

2. 或(or)
该操作符也需要两个操作数,而且这两个操作数都应该是布尔类型的。如果有一个操作数的值是 True,那么运算结果就是 True;否则结果是 False。

表2:或运算规则

ABA or B
True True True
True False True
False True True
False False False


下面是实际操作的情况:

>>> True or True   # 演示布尔类型的or运算
True
>>> True or False
True
>>> False or True
True
>>> False or False
False

3. 非(not)
该操作符需要一个操作数,要求操作数是布尔类型的。如果操作数是 True,那么结果是 False;如果操作数的值为 False,那么结果就是 True。

表3所示为其运算规则。

表3:非运算规则

Anot A
True False
False True

4.示例:

判断print(1 > 2 and 3 or 4 and 3 < 2 or not 4 > 5)输出什么?

step1: print(1 > 2 and 3 or 4 and 3 < 2 or true)    # not 4 > 5 为 True
step2: print(false and 3 or 4 and false or true)    # 1 > 2 为 False,3 < 2 为 False
step3: print(false or false or true)
       * false and 3,因为false为假所以and不再运算直接返回False;
       * 4 and false,因为4为真,所以and运算符会继续运算后面的,and只要有一个为假,即结果为假,所以返回False
step4: print(false or true)     # false or false 为假
step5: print(true)              # false or true 为 True
返回 TRUE

 

posted @   渐逝的星光  阅读(321)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示