您的位置:首页 > 编程语言 > Python开发

python and or用法详解

2019-06-26 14:15 3547 查看

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,这边就不做详细介绍了。文章观点如有什么错误的地方,欢迎指正。

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python and or