对于包含and运算的表达式,Python解释器将从左到右扫描,返回第一个为假的表达式值,无假值则返回最后一个表达式值。下面看一个使用and的例子:# if all the expressions are true, return the last expressionprint {"name": "Will"} and "hello" and 1# return the first false expressionprint {"name": "Will"} and "" and 1print {"name": "Will"} and [] and 1print {} and [] and Noneprint {"name": "Will"} and [1] and None代码的输出为下:
逻辑或-or
对于包含or运算的表达式,Python解释器将从左到右扫描,返回第一个为真的表达式值,无真值则返回最后一个表达式值。看下面的例子:# if all the expressions are false, return the last expressionprint {} or [] or None# return the first true expressionprint {"name": "Will"} or "hello" or 1print {} or [1] or 1print {} or [] or "hello"代码的输出如下:
三目运算符
很多语言中都支持三目运算符"bool?a:b",虽然在Python中不支持三目运算符,但是可以通过and-or达到同样的效果。expression_1 and expression_2 or expression_3看代码:a = "hello"b = "will"# bool?a:bprint True and a or bprint False and a or b这个例子通过and-or模拟了三目运算符,当第一个表达式expression_1为True的时候,整个表达式的值就是expression_2表达式的值:
安全的and-or
其实上面使用and-or模拟三目运算符的方式并不安全,看下图:如果expression_2本身的值就是False,那么无论expression_1的值是什么,"expression_1 and expression_2 or expression_3"的结果都会是expression_3。可以通过简单的代码就行验证:a = []b = "will"# bool?a:bprint True and a or bprint False and a or b代码输出为:那么为了避免这种问题,可以使用下面的方法,将expression_2和expression_3存放在list中:(expression_1 and [expression_2] or [expression_3])[0]例如:a = []b = "will"# bool?a:bprint (True and [a] or [b])[0]print (False and [a] or [b])[0]代码的运行效果为下,即使expression_2为False,但是[expression_2]仍是非空列表:
总结
本文通过一些简单的例子,演示了Python中and和or的使用。并通过and-or方式实现了三目运算符的效果。无需操作系统直接运行 Python 代码 http://www.linuxidc.com/Linux/2015-05/117357.htmCentOS上源码安装Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里 Python 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-07/119824.htm