歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python中的and/or

Python中的and/or

日期:2017/3/1 9:27:45   编辑:Linux編程

在Python中,可以通過and,or和not進行邏輯運算,下面就來看看and和or的簡單介紹。

邏輯與-and

對於包含and運算的表達式,Python解釋器將從左到右掃描,返回第一個為假的表達式值,無假值則返回最後一個表達式值

下面看一個使用and的例子:

# if all the expressions are true, return the last expression
print {"name": "Will"} and "hello" and 1

# return the first false expression
print {"name": "Will"} and "" and 1
print {"name": "Will"} and [] and 1
print {} and [] and None
print {"name": "Will"} and [1] and None

代碼的輸出為下:

邏輯或-or

對於包含or運算的表達式,Python解釋器將從左到右掃描,返回第一個為真的表達式值,無真值則返回最後一個表達式值

看下面的例子:

# if all the expressions are false, return the last expression
print {} or [] or None

# return the first true expression
print {"name": "Will"} or "hello" or 1
print {} or [1] or 1
print {} or [] or "hello"

代碼的輸出如下:

三目運算符

很多語言中都支持三目運算符"bool?a:b",雖然在Python中不支持三目運算符,但是可以通過and-or達到同樣的效果。

expression_1 and expression_2 or expression_3

看代碼:

a = "hello"
b = "will"

# bool?a:b
print True and a or b
print 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:b
print True and a or b
print False and a or b

代碼輸出為:

那麼為了避免這種問題,可以使用下面的方法,將expression_2和expression_3存放在list中:

(expression_1 and [expression_2] or [expression_3])[0]

例如:

a = []
b = "will"

# bool?a:b
print (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.htm

CentOS上源碼安裝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.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved