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

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

python and 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:当所有条件为真时,该条件即为真。逻辑图如下:

python and 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'这个条件,这是为什么呢"htmlcode">

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

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

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com