亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

?python 中的條件判斷語句的使用介紹

 更新時(shí)間:2022年03月18日 10:28:14   作者:Steven迪文  
這篇文章主要介紹了?python 中的條件判斷語句的使用,主要學(xué)習(xí)內(nèi)容有封裝過于復(fù)雜的邏輯判斷,不同分支下的重復(fù)代碼等,更多相關(guān)內(nèi)容,需要的小伙伴可以參考下面文章詳細(xì)介紹內(nèi)容

1. 避免多層分支嵌套

Python中利用縮進(jìn)來替代 { }。如果多個 if 嵌套, 堪稱 ” 嵌套 if 地獄 “

下面的代碼直接翻譯了原始條件分支,導(dǎo)致代碼可讀性和維護(hù)性很差。

def buy_fruit(nerd, store):
? ? """去水果店買蘋果
? ??
? ? - 先得看看店是不是在營業(yè)
? ? - 如果有蘋果的話,就買 1 個
? ? - 如果錢不夠,就回家取錢再來
? ? """
? ? if store.is_open():
? ? ? ? if store.has_stocks("apple"):
? ? ? ? ? ? if nerd.can_afford(store.price("apple", amount=1)):
? ? ? ? ? ? ? ? nerd.buy(store, "apple", amount=1)
? ? ? ? ? ? ? ? return
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? nerd.go_home_and_get_money()
? ? ? ? ? ? ? ? return buy_fruit(nerd, store)
? ? ? ? else:
? ? ? ? ? ? raise MadAtNoFruit("no apple in store!")
? ? else:
? ? ? ? raise MadAtNoFruit("store is closed!")

我們利用取反的方式,“提前結(jié)束” 來優(yōu)化這段代碼:

def buy_fruit(nerd, store):
? ? if not store.is_open():
? ? ? ? raise MadAtNoFruit("store is closed!")

? ? if not store.has_stocks("apple"):
? ? ? ? raise MadAtNoFruit("no apple in store!")

? ? if nerd.can_afford(store.price("apple", amount=1)):
? ? ? ? nerd.buy(store, "apple", amount=1)
? ? ? ? return
? ? else:
? ? ? ? nerd.go_home_and_get_money()
? ? ? ? return buy_fruit(nerd, store)

“提前結(jié)束” :指在函數(shù)內(nèi)使用 return 或 raise 等語句提前在分支內(nèi)結(jié)束函數(shù)。

利用逆向思維,當(dāng)分支條件不滿足時(shí),我們直接結(jié)束這段代碼,這樣更容易閱讀。

2. 封裝過于復(fù)雜的邏輯判斷

如果條件分支中有過多的判斷條件 and | not | or, 可以將這樣的部分封裝起來。

if person.is_student and person.age > 20 and person.is_male:
?? ?pass

這樣封裝的部分更有可解釋性,更容易被人理解。
最重要的事還解決了,相同代碼多次出現(xiàn)的問題。

if person.identity() and person.gender():
?? ?pass

3. 不同分支下的重復(fù)代碼

下面的代碼很難讓人直觀分別出不同:

if person.is_student():
?? ?record_imformation(
?? ?name = person.name,
?? ?age = person.name,
?? ?address = person.address,
?? ?student_number = 10011,
?? ?recorded = now(),
?? ?)
else:
?? ?update_information(
?? ?name = person.name,
?? ?age = person.name,
?? ?address = person.address,
?? ?updated = now(),
?? ?)

關(guān)注這些由分支產(chǎn)生的重復(fù)代碼塊,通過轉(zhuǎn)化簡化它們。

if person.is_student():
?? ?imformation_func = ?record_imformation
?? ?extra_args = {'student_number' : 10011, 'recorded' : now() }
else:
?? ?imformation_func = update_information
?? ?extra_args = {'updated' : now() }

information_func(
?? ?name = person.name,
?? ?age = person.name,
?? ?address = person.address,
?? ?**extra_args
)

4. 合理使用三元表達(dá)式

使用普通的if / else 語句 代碼可讀性通常更好。
對于三元表達(dá)式只處理簡單的邏輯分支即可。

language = "python" if you.favor("dynamic") else "golang"

5. 常見技巧

5.1德摩根定律

對于下面的代碼,很難第一時(shí)間 get 到邏輯關(guān)系。

# 如果用戶沒有登錄或者用戶沒有使用 chrome,拒絕提供服務(wù)
if not user.has_logged_in or not user.is_from_chrome:
? ? return "our service is only available for chrome logged in user"

而使用德摩根定律。

not A or not B = not (A and B), 代碼讀起來會容易很多。

if not (user.has_logged_in and user.is_from_chrome):
? ? return "our service is only available for chrome logged in user"

5.2自定義類的魔法方法

python提供了跟多自定義類的魔法方法,我們可以利用它門,讓我們的代碼更加pythonic。

下面的代碼用到了len() 函數(shù)。

class UserCollection(object):

? ? def __init__(self, users):
? ? ? ? self._users = users


users = UserCollection([piglei, raymond])

if len(users._users) > 0:
? ? print("There's some users in collection!")

通過給類自定義魔法方法,分支條件變得更加簡單。
并且可以自己控制魔法方法的返回值。

class UserCollection:

? ? def __init__(self, users):
? ? ? ? self._users = users

? ? def __len__(self):
? ? ? ? return len(self._users)


users = UserCollection([piglei, raymond])

# 定義了 __len__ 方法后,UserCollection 對象本身就可以被用于布爾判斷了
if users:
? ? print("There's some users in collection!")

5.3在條件判斷中使用 all() / any()

  • all (x) : x 中所有對象都為真時(shí)返回 True, 否則 False
  • any (x): 只要 x 中一個對象為真時(shí)返回 True, 否則 False
def all_numbers_gt_10(numbers):
? ? """僅當(dāng)序列中所有數(shù)字大于 10 時(shí),返回 True
? ? """
? ? if not numbers:
? ? ? ? return False

? ? for n in numbers:
? ? ? ? if n <= 10:
? ? ? ? ? ? return False
? ? return True

使用all ( )內(nèi)建函數(shù),再配合生成器表達(dá)式。

def all_numbers_gt_10_2(numbers):
? ? return bool(numbers) and all(n > 10 for n in numbers)

5.4使用 try/while/for 中 else 分支

def do_stuff():
? ? first_thing_successed = False
? ? try:
? ? ? ? # ...
? ? ? ? first_thing_successed = True
? ? except Exception as e:
? ? ? ? # ...
? ? ? ? return

? ? # 僅當(dāng) first_thing 成功完成時(shí),做第二件事
? ? if first_thing_successed:
? ? ? ? return do_the_second_thing()

其實(shí),我們可以用更簡單的方法達(dá)到同樣的效果:

def do_stuff():
? ? try:
? ? ? ? # ...
? ? except Exception as e:
? ? ? ? # ...
? ? ? ? return
? ? else:
? ? ? ? return do_the_second_thing()

try 的語句塊后面加上 else 分支。
類似的 for / while 也支持 else 分支。

6. 常見陷阱

6.1與 None 值得比較

在 python 中, == 與 is 兩種比較方法有根本的區(qū)別。

  • == : 僅比較兩者的值是否一致
  • is : 比較兩者是否指向內(nèi)存中的同一份地址。

但是 None 在 python 中是一個單例對象,如果要判斷某個變量是否為 None 要用 is, 只有 is 才嚴(yán)格意義上表示某個變量是否為None

5.2and 和 or 的運(yùn)算優(yōu)先級

and 的優(yōu)先級大于 or

即使執(zhí)行的優(yōu)先級如我們想要的一致,也要采取額外括號的方式讓代碼更清晰。

(True or False) and False # False
True or False and False # True

此外:

c and a or b 不是總能給出正確的結(jié)果。只有當(dāng) a 與 b 的布爾值為真時(shí),這個表達(dá)式才正常工作,因?yàn)檫壿嬤\(yùn)算的短路特性。

到此這篇關(guān)于 python 中的條件判斷語句的使用介紹的文章就介紹到這了,更多相關(guān) python 條件判斷語句內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論