Python3使用獨立的if語句與使用if-elif-else結構的不同之處
if-eliff-else結構功能強大,但是僅適合用于只有一個條件滿足的情況:遇到通過了的測試后,Python就跳過余下的測試。
然而,有時候必須檢查你關心的所有條件。在這種情況下,應使用一系列不包含else和else代碼塊的簡單if語句
下面來看一個早餐店的實例。如果顧客點了一個雞蛋卷,并點了兩種種配料,要確保這個雞蛋卷包含這些配料
toopings.py
requested_toppings = ['pepperoni','mushrooms']
if 'pepperoni' in requested_toppings:
print("Adding pepperoni")
if 'lettuce' in requested_toppings:
print("Adding lettuce")
if 'potato' in requested_toppings:
print("Adding potato")
if 'mushrooms' in requested_toppings:
print("Adding mushrooms")
print("\nFinished making your breakfast!")
輸出:
Adding pepperoni
Adding mushrooms
Finished making your breakfast!
首先創建了一個列表,其中包含顧客點的配料。然后第一個 if 語句檢查是否顧客點了配料辣香腸(‘pepperoni’),因為接下來也是簡單的 if 語句,而不是 elif和else 語句,所以不管前一個測試是否通過, 都將進行這個測試。 然后第二,三個的 if 語句判斷沒點 生菜(‘lettuce’)和 土豆(‘potato’),判斷第四個 if 點了 蘑菇(‘mushrooms’)。每當這個程序運行時,都會進行這三個獨立的測試。
requested_toppings = ['pepperoni','mushrooms']
if 'pepperoni' in requested_toppings:
print("Adding pepperoni")
elif 'lettuce' in requested_toppings:
print("Adding lettuce")
elif 'potato' in requested_toppings:
print("Adding potato")
elif 'mushrooms' in requested_toppings:
print("Adding mushrooms")
print("\nFinished making your breakfast!")
輸出:
Adding pepperoni
Finished making your breakfast!
第一個測試檢查列表是否包含‘pepperoni’,通過了,因此將此辣香腸添加。但是將跳過其余if-elif-else結構中余下的測試。
總之, 如果只想執行一個代碼塊, 就使用if-elif-else結構;如果要運行多個代碼塊,就使用一些獨立的 if 語句。
轉載自:https://blog.csdn.net/viviliao_/article/details/79561651