三目運算符也就是三元運算符
一些語言(如Java)的三元表達(dá)式形如:
判定條件?為真時的結(jié)果:為假時的結(jié)果
result=x if x
Python的三元表達(dá)式有如下幾種書寫方法:
if __name__ == '__main__': a = '' b = 'True' c = 'False' #方法一:為真時的結(jié)果 if 判定條件 else 為假時的結(jié)果 d = b if a else c print('方法一輸出結(jié)果:' + d) #方法二:判定條件 and 為真時的結(jié)果 or 為假時的結(jié)果 d = a and b or c print('方法二輸出結(jié)果:' + d) #以上兩種方法方法等同于if ... else ... if a: d = b else: d = c print('if語句的輸出結(jié)果:' + d)
輸出結(jié)果:
說明:
判斷條件:a為空串,所以判斷條件為假
當(dāng)判斷條件為真時的結(jié)果:d = b
當(dāng)判斷條件為假時的結(jié)果:d = c
x = [x for x in range(1,10)] print(x) y =[] result = True if 12 not in x else False # this is the best way print(result) result = True if not 12 in x else False # this way just like as " (not 12) in x" print(result) print(x is y) print(x is not y) # this is the best way print(not x is y) # this way just like as " (not x ) is y" ,so upper is the best way result = 2 if 1 < 2 else 5 if 4 > 5 else 6 # just as 1 > 2 ? 2 : 4 > 5 ? 5 : 6 print(result)
python中的not具體使用及意思
name='' while not name: name=raw_input(u'請輸入姓名:') print name
python中的not具體表示是什么:
在python中not是邏輯判斷詞,用于布爾型True和False,not True為False,not False為True,以下是幾個常用的not的用法:
(1) not與邏輯判斷句if連用,代表not后面的表達(dá)式為False的時候,執(zhí)行冒號后面的語句。比如:
a = False if not a: (這里因為a是False,所以not a就是True) print "hello"
這里就能夠輸出結(jié)果hello
(2) 判斷元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,這句話的意思是如果a不在列表b中,那么就執(zhí)行冒號后面的語句,比如:
a = 5 b = [1, 2, 3] if a not in b: print "hello"
這里也能夠輸出結(jié)果hello
not x???? 意思相當(dāng)于???? if x is false, then True, else False
代碼中經(jīng)常會有變量是否為None的判斷,有三種主要的寫法:
第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。
如果你覺得這樣寫沒啥區(qū)別,那么你可就要小心了,這里面有一個坑。先來看一下代碼:
>>> x = 1 >>> not x False >>> x = [1] >>> not x False >>> x = 0 >>> not x True >>> x = [0] # You don't want to fall in this one. >>> not x False
更多內(nèi)容可以參考這篇文章://www.jb51.net/article/93165.htm
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
