天天看點

Python中條件判斷 if, elif, else的使用

每種語言都有條件判斷語句 if/else。學習python大半年,自以為對于if/else語句很熟練,不料今天還是掉坑裡了。好不容易搞明白後,趕緊記下來,并分享給大家!

1. 用法說明

  • 一個if語句 + 一個else 語句:      

       當if 判斷為True時,執行if語句下的代碼; 而當if判斷為False時,執行else語句下面的代碼。

  • n個if語句(n>=2)   +   最後一個else語句:   

      每一個if語句都會被判斷,不管它之前的if判斷的是True或者False。 判斷為True的if語句,其對應的代碼會被執行,而為False時則不執行,直接跳到下一個if判斷。

      而else語句隻有當第n個if(即else前一個if)為False時才執行。若第n個if為True, 則不執行else語句對應的内容。

  • 一個if語句    +   n 個 elif語句 (n >=1)    +   一個else語句:

     按照先後順序進行判斷,若目前條件(if 或者是 elif) 為False, 則跳到下一個條件進行判斷,否則為True時,執行對應的代碼,并且後面還未執行的條件判斷都跳過,不再執行了。

     即隻要遇到一個if或elif為True的, 程式執行完對應的代碼後,該輪條件判斷就結束了。

2. 執行個體示範

2.1 n個if語句(n>=2)   +   最後一個else語句

首先看一段簡單的代碼,判斷兩個數值誰大。這裡我使用的是python 3.6

def bigger_1(a,b):
    if a > b:  
        print ("%s is bigger" % a)
    if a < b:
        print ("%s is bigger" % b)
    else:
        print("%s is equal to %s" % (a, b))
    return 'The end'
           

初看代碼是沒有問題的,如果a > b, 輸入 a is bigger; 如果a < b, 輸出 b is bigger; 否則就輸出a is equal to b。

但是實際運作時就發現問題了。

In[24]: bigger_1(5,11)
11 is bigger
Out[24]: 'The end'
           
In[25]: bigger_1(10,6)
10 is bigger
10 is equal to 6
Out[25]: 'The end'
           
In[26]: bigger_1(2,2)
2 is equal to 2
Out[26]: 'The end'
           

bigger_1(10, 6)列印出了兩條結果,說明它即通過了第一個if a>b的判斷,也執行了else。

這是因為程式對每一條if語句都進行了判斷。

bigger_1(10, 6): 第一個if a>b為True, 是以輸出10 is bigger。但是程式還是會接着對第二個if進行判斷,第二個if a <b為False, 是以程式就直接跳到else, 執行else對應的代碼,輸出了10 is equal to 6 這樣的結果。

else可以了解為其前一個if的互補條件,若前一個if為True, else就會False, 反之else為True。 具體到上面的代碼,else就等價于 if a >= b了。

bigger_1(5,11): 第一個if為false, 轉到判斷第二個if,第二個if a<b為True, 是以輸出 11 is bigger。由于第二個if 為 True, 是以else就是False,不執行了。

bigger_(2, 2): 第一個if為false, 轉到判斷第二個if,由于第二個if 為 False,  是以else就是True,執行。

将上面代碼稍微修改一下,把最後一個else 改為 if a == b, 這就把每條判斷語句都變成了硬判斷(即限定死了為True的條件)。發現結果就沒有問題了。

def bigger_2(a,b):
    if a > b:
        print ("%s is bigger" % a)
    if a < b:
        print ("%s is bigger" % b)
    if a == b:
        print("%s is equal to %s" % (a, b))
    return 'The end'
           
In[29]: bigger_2(10,6)
10 is bigger
Out[29]: 'The end'

In[30]: bigger_2(5,11)
11 is bigger
Out[30]: 'The end'

In[31]: bigger_2(2,2)
2 is equal to 2
Out[31]: 'The end'
           

2.2 一個if語句    +   n 個 elif語句 (n >=1)    +   一個else語句

在進一步,保留else, 而将第二個if換成elif,elif是else if的簡寫格式。發現代碼運作也沒有問題了。

def bigger_3(a,b):
    if a > b:
        print ("%s is bigger" % a)
    elif a < b:
        print ("%s is bigger" % b)
    else:
        print("%s is equal to %s" % (a, b))
    return 'The end'
           
In[33]: bigger_3(10,6)
10 is bigger
Out[33]: 'The end'

In[34]: bigger_3(5,11)
11 is bigger
Out[34]: 'The end'

In[35]: bigger_3(2,2)
2 is equal to 2
Out[35]: 'The end'
           

bigger_3(10, 6): if a> b 判斷為True後,後面的elif和else都直接跳過了。

bigger_3(5, 11): 第一個if為False, 轉到判斷elif, elif為True, 執行代碼,且後面的else就跳過忽略了。

bigger_3(2, 2): if 和elif都為False, 是以執行else對應的輸出語句。

完畢!!!