今天給大家分享一下Python中的IF語句的使用場景以及注意事項。主要內容如下:
- 1.python中的真假
- 2.Python操作符
- 3.if語句實例和嵌套實例
- 4.if語句中的if嵌套實例
- 5.and和or的運算關系演示
首先我們看一個IF語句處理的流程圖:
IF語句運行原理就是:給出條件,決定下一步怎么做?如果條件為真,就執行決策條件代碼塊的內容,為假就退出。
我們學習之前先看下Python中的真假:在python中,任何非零,非空對象都是真,除真和None以外其他的都是假。
來敲一下筆記:
- 1.任何非零和非空對象都為真 解釋為True
- 2.數字0、空對象和特殊對象None均為假 解釋為False
- 3.比較和相等測試會應用到數據結構中
- 4.返回值為True或False
我們來看幾個例子細細品味一下:
>>> not 0 True >>> not 1 False >>> not [] True >>> not [1] False >>> not True False >>> not False True
ok,你知道了真假以后,然后我們來簡單介紹一下python中的常用的幾種運算符.因為條件語句和運算符的結合是經常會用到的。
Python操作符介紹
1.算術運算符 + - * / (取商) %(取余數) **
2.賦值運算符 num=100 num = num + 90
3.成員關系運算符 in not in
4.比較運算符 > < >= < = == != <>
接下來看一下關於IF語句中的一些常用的實例......
1.if語句基本構成
if 條件: if語句塊 else: else語句
if語句用於比較運算(大於>)中
a = 0 if a > 0: print "a is not 0"
else: print 'a is o'
if語句用於比較運算中結合邏輯運算符
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'
2.if結合比較運算操作符: >< == >= <= == != <>
a =90 b =100
if a>b: print "a is max"
else: print 'a is min'
IF語句結合不等於實例:
a =90 b =100
if a<>b: print "a is max"
else: print 'a is min'
IF語句結合成員關系運算符:In (not in )
name = 'zhangshan'
if 'zhang' not in name: print 'zhang is in name'
else: print 'zhang 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 "{} 大於 {}".format(number1,number2) elif number2 < number2: print "{} 小於 {}".format(number1,number2) elif number1 == number2: print '%s 等於 %s'%(number1,number2) else: print 'game is over'
IF嵌套語句2
最外側if語句作為整個if語句中的決策條件,優先滿足后,才可以繼續和if子句進行在判斷,如果一開始輸入的內容不符合決策條件,就直接退出整個if分支語句。
name = input("請輸入信息:") if name.endswith('hello'): if name.startswith('china'): print 'welcome to {}'.format(name) elif name.startswith('japan'): print 'say you {}'.format(name) else: print '輸入有誤,重新輸入'
else: print '游戲結束---->'
寫在最后補充-對Python而言:
其一, 在不加括號時候, and優先級大於or 其二, x or y 的值只可能是x或y. x為真就是x, x為假就是y 其三, x and y 的值只可能是x或y. x為真就是y, x為假就是x
看幾個實際的例子
>>> 5 and 6 and 7 7 >>> 4 and 5 or 6 and 7 5 >>> True or True and False True >>>