python中not、and、or的優先級


        <div class="article-info-box">
            <div class="slide-content-box">
                                                                                                                                                
                                                                            </div>
        </div>
    </div>
</div>
<article class="baidu_pl">
    <!--python安裝手冊開始-->
            <!--python安裝手冊結束-->
             <div class="article_content clearfix" id="article_content">
        <!--一個博主專欄付費入口-->
                      <!--一個博主專欄付費入口結束-->
        <link href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-833878f763.css" rel="stylesheet">
                                    <link href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-833878f763.css" rel="stylesheet">
            <div class="htmledit_views" id="content_views">
                                        <p>今晚做題的時候,看到一道關於優先級的題目,我頓時蒙了???</p>

為什么 0 and 1 返回的是0?為什么 3 and 4卻返回的是4?

天吶?這到底是為什么???不知道初學的小白是否也有着跟我一樣的困惑?

經過不停的翻閱資料,看大牛們的博客,我頓時明白了

首先要知道優先級順序:not>and>or

其次要知道在Python中所有的空字符串都是假,非空字符串都是真,非零的數字都是真。要重點記住!

接着要知道下面這幾個知識點!敲黑板划重點啦

對於and:

  • 只要左邊的表達式為真,那么整個表達式返回的是右邊表達式的值,否則返回的是左邊表達式的值
  • 換言之,x and y 的值只能是x 和 y,x為真時就是y,x為假就是x

對於or

  • 只要兩邊的表達式都為真,整個表達式的結果返回的是左邊表達式的值;
  • 如果一真一假,返回真值表達式的值;
  • 如果兩個值都假,比如空值和0,返回的是右邊的值(空值或0)
  • 換言之,x or y 的值只可能是 x 和 y,x為真就是x,x為假就是y

對於not x:

  • x為假,輸出True
  • x為真,輸出False

emmm...看起來,x and y 與 x or y 的返回結果是相反的

下面舉栗子來詳細說明:

(False or 5)輸出5                #False為假,在or中,x為假—>輸出y

(5 or False)輸出5                #5為真,在or中,x為真—>輸出x

(0 or False)輸出False         # 0是假 

(True or 3)輸出True            #True為真

(2 or True)輸出2                 #2為真

(0 or True)輸出True            #0為假

(True or False)輸出True     #True為真

(True and  4)輸出4             #True為真,在and中,x為真—>輸出y

(1 and True)輸出True         #1為真

(False and 1)輸出False      #False為假,在and中,x為假—>輸出x

(1 and False)輸出False      

(0 and  True)輸出0

(not 3)輸出False                #3為真,在not中,x為真—>輸出False

(not 0)輸出True             

注意:布爾類型bool是特殊的整型,True相當於1,False相當於0

 

                        </div>
                </div>
</article>
版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接: https://blog.csdn.net/dafeidouzi/article/details/98992689


免責聲明!

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



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