python中if條件判斷

.python中的真假python

if語句運行原理就是:給出條件,決定下一步怎麼作?若是條件爲真,就執行決策條件代碼塊的內容,爲假就退出。數據結構

咱們學習以前先看下Python中的真假:在python中,任何非零,非空對象都是真,除真和None之外其餘的都是假。學習

  • 1.任何非零和非空對象都爲真 解釋爲True
  • 2.數字0、空對象和特殊對象None均爲假 解釋爲False
  • 3.比較和相等測試會應用到數據結構中
  • 4.返回值爲True或False

 

二.Python操做符介紹

算術運算符  + (加)  -(減)  *(乘)   / (取商)    //(取整)  %(取餘)  **(次方)
賦值運算符 =  +=     -=  *=   /=  //=  %=  **= 成員關係運算符 in    not in 比較運算符 >(大於)   < (小於)   >=(大於等於)    < =(小於等於)    ==(等於)   !=(不等於) 

 

三.if語句
測試

1.if語句基本構成spa

  if 條件:     if語句塊   else:       else語句塊

 

注意:if條件寫完後要用冒號結尾3d

 

2.if語句應用示例code

if語句用於比較運算對象

a = 0 if a > 0: print "a is not 0" else: print 'a is o'

if語句用於比較運算中結合邏輯運算符blog

a = 50
if a< 100 and a > 10: print "a is not 0" else: print 'a is false'

and的優先級大於or,有括號的運算最優先遊戲

a = 50
if (a< 100 and a > 10 or (a >20 and a<100): print "a is true" else: print 'a is false'

if結合比較運算操做符

a =90 b =100 if a>b: print "a is max" else: print 'a is min'

 

if語句結合成員關係運算符

name  = 'xiaoming' if 'xm' not in name: print 'xm is in name' else: print 'xm is not in name'

 

3.if elif的嵌套結構

if 條件: if語句塊 elif 條件: elif語句塊 else: else語句塊

用於檢查多個條件是否知足:

複製代碼
number1 = int(input("請輸入數字1:")) number2 = int(input("請輸入數字2:")) if number1 > number2: print "%d 大於 %d" %(number1,number2) elif number2 < number2: print "%d 小於 %d" %(number1,number2) elif number1 == number2: print '%d 等於 %d'%(number1,number2) else: print 'game is over'
複製代碼

 

 

3.if嵌套

複製代碼
name = 'hello xiao mi' if 'hello' in name: if 'xiao' in name:
  if ' mi' in name: print name else: print '輸入有誤,從新輸入' else: print '遊戲結束---->'
複製代碼

 

 

寫在最後的補充:

 在不加括號時候, and優先級大於or
  x or y 的值只多是x或y.  x爲真就是x, x爲假就是y
  x and y 的值只多是x或y.  x爲真就是y, x爲假就是x
相關文章
相關標籤/搜索