短路運算符
你知道Python中的短路運算符指哪兩個嗎?
答案:and
, or
爲什麼被稱爲短路運算符?
這是因爲一旦可以確定結果,解析就會停止。解析的順序是從左至右,所以後邊運算不執行,因此被形象的稱作短路。
以上理解起來有些抽象,舉幾個例子一看就明白。
請看下面代碼:
代碼1:
a = ''
b = a and 'i will not execute'
print(b)
打印結果爲:``,因爲and
運算符從左到右檢查,一旦a
爲空即爲假,則結果已確定爲假,'i will not execute'
被短路。
代碼2:
a = 'python'
b = a or 'i will not execute'
print(b)
打印結果爲:python
,因爲or
運算符從左到右檢查,一旦a
爲真則結果已確定爲真,所以'i will not execute'
被短路。
更多Python類原創文章: