python and or用法详解

(编辑:jimmy 日期: 2024/9/28 浏览:2)

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

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

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。