python and or用法


      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,這邊就不做詳細介紹了。文章觀點如有什么錯誤的地方,歡迎指正。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM