python 逻辑运算符 and or

https://www.cnblogs.com/white-small/p/6260740.html

 

1 Python逻辑运算符

Python语言支持逻辑运算符,以下假设变量 a 为 10, b为 20:

运算符逻辑表达式描述实例
andx and y布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。(a and b) 返回 20。
orx or y布尔"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。(a or b) 返回 10。
notnot x布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。not(a and b) 返回 False

 

2列表的逻辑运算

会把整个列表作为一项,判断是0或1,因此只要列表不空,也为1.

例如:

[1 ,0] and [3,0]

Out: [3, 0]

[0 ,0] and [3,0]

Out: [3, 0]

0 and [3,0]

Out: 0

[] and [3,0]

Out: []

 

3示例

and 和 or 是python的两个逻辑运算符,可以使用and , or来进行多个条件内容的判断。下面通过代码简单说明下and  or的用法:

1. or:当有一个条件为真时,该条件即为真。逻辑图如下:

测试代码如下:

a=raw_input('please input somting:')
if a=='a'  or a=='b':
    print 'it is a or b'
else:
    print 'it is not a or b'

 执行代码,输入a,b,ac,结果如下:

复制代码

please input somting:a
it is a or b

please input somting:b
it is a or b

please input somting:ac
it is not a or b

复制代码

     通过这个例子,我们可以看出,当输入为a或者b时,满足 a==‘a’或者a=='b'的条件,即满足if条件。

2.or:当所有条件为真时,该条件即为真。逻辑图如下:

测试代码如下:

a=raw_input('please input somting:')
if a!='a'  and a!='b':
    print 'it is not a or b'
else:
    print 'it is a or b'

执行代码,输入a,b,ac,结果如下:

复制代码

please input somting:a
it is  a or b

please input somting:b
it is  a or b

please input somting:ac
it is not a or b

复制代码

      通过这个例子,我们可以看出,只有当条件同时满足a!='a' 和 a!='b'时,才会执行  print 'it is not a or b' 

3.为了深入了解and  or的用法,考虑到当a='a' or 'b'或者a='a' and 'b'时,会是怎么样子的呢。让我们先测试or的用法看下,测试代码如下:

a=raw_input('please input somting:')
if a=='a' or 'b':
    print 'it is  a or b'
else:
    print 'it is not a or b'

我们输入a,b,q,结果如下:

复制代码

please input somting:a
it is  a or b


please input somting:b
it is  a or b

please input somting:q
it is  a or b

复制代码

我们发现,无论输入什么,都满足a==‘a’ or 'b'这个条件,这是为什么呢?这时,我们看下or的运算原理:or是从左到右计算表达式,返回第一个为真的值。由于我们并没有将比较值‘a’ or 'b'用括号或者双引号集合起来,所以当我们输入q时,虽然输入q=='a'这个条件不成立,当时,此时判断条件变成了q=='a' or 'b',此时'b'不会空,当两个条件之一有一个为真,这个判断条件就是Ture,所以无论我们输入什么,都是为Ture。我们可以稍微修改代码,验证下or的运算原理:or是从左到右计算表达式,返回第一个为真的值。测试代码如下:

a=raw_input('please input somting:')
if a==('a' or 'b'):
    print 'it is  a or b'
else:
    print 'it is not a or b'

我们输入a和b,结果如下:

please input somting:a
it is  a or b


please input somting:b
it is not a or b

因为‘a’ or ‘b’这个条件,‘a’为第一个真值,所以这个条件其实返回的是‘a’,所以只有当输入为a,时,才执行了  print 'it is a or b' 。

4.and  :从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值。对于and的测试,同于or,这边就不做详细介绍了。文章观点如有什么错误的地方,欢迎指正。


版权声明:本文为lzp_k2原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。