# If-Else 條件判斷 if-else 條件判斷是以敘述產生的布林值(Boolean)作為判斷依據,透過布林值的True或False來決定執行或不執行動作。 | True | False | | ---- | ------ | | 條件為真 |條件為假 | 執行 | 不執行 | ## 一、if 敘述 `if` 用法為如果達成某一條件( 敘述為真 ),則執行某一動作,舉個例子:*`如果有錢,就去買書`*,其中的 *`有錢`* 就是條件; *`買書`* 就是達成條件而執行的動作。 ### 1. 程式的寫法 ``` if (條件): 動作 ``` #### 注意:<font color="#f00"> :star:要記得縮排!!!</font> 所以以程式表達上述例子就是: ``` if(有錢): 買書 ``` --- ### 2. if 敘述的應用 **使用者輸入一個數字(整數),若此數字大於等於60,則輸出"Pass"** > 範例 ```python=1 score = int(input()) if (score>=60): print("Pass") ``` >輸入 ``` 80 ``` >輸出 ``` pass ``` --- ## 二、if-else 敘述 如果要在無法達成條件時執行另外的動作,則使用 `else`,例如:*`如果有錢,就去買書;沒錢則睡覺`*, `睡覺` 就是沒達成條件下執行的動作。 ### 1. 程式的寫法 ```python=1 if (條件): 動作1 else: 動作2 ``` 所以以程式表達上述例子就是: ```python=1 if (有錢): 買書 else: 睡覺 ``` --- ### 2. if-else 敘述的應用 **使用者輸入一個數字(整數),若此數字大於等於60,則輸出"Pass";否則輸出"Fail"** >範例 ```python=1 score = int(input()) if (score>=60): print("Pass") else: print("Fail") ``` --- ## 三、if-elif-else 敘述 如果條件為兩個以上時,則可使用 `elif` ,例如:*`如果有錢,就去買書;有兌換券就去換書;沒錢也沒兌換券就去睡覺`* 就可以使用 `elif` 。 #### 注意:<font color="#f00"> :star:elif 個數沒有限制,由個人需求決定。</font> ### 1. 程式的寫法 ```python=1 if (條件1): 動作1 elif (條件2): 動作2 else: 動作3 ``` 所以以程式表達上述例子就是: ```python=1 if (有錢): 買書 elif (有兌換券): 換書 else: 睡覺 ``` --- ### 2. if-elif-else 敘述的應用 **使用者輸入一個數字(整數),若此數字大於等於80,則輸出"Perfect";大於等於60且小於80則輸出"Awesome";否則輸出"Very good"** >範例 ```python=1 score = int(input()) if (score>=80): print("Perfect") elif (score>=60): print("Pass") else: print("Fail") ``` >輸入 ``` 78 ``` >輸出 ``` Pass ``` --- ## 四、巢狀判斷 「巢狀判斷」表示「一個判斷式裡,還有另外 n 個判斷」,就像鳥巢一般層層判斷下去。 ### 1. 程式舉例 ```python=1 if ( 條件1 ) : if ( 條件2 ) : 動作1 elif ( 條件3 ) : 動作2 else : 動作3 else: 動作4 ``` --- ### 2. 巢狀判斷的應用 **整數類型判斷:輸入任意一數(整數),若此數大於0則輸出"正整數",並繼續判斷此數是偶數或奇數,偶數則輸出"偶數",奇數輸出"奇數";若此數小於0,則輸出"負整數";若此數等於0,則輸出"0"** >範例 ```python=1 num = int(input()) if num > 0: print("正整數") if num % 2 == 0: print("偶數") else: print("奇數") elif num == 0: print("0") else: print("負整數") ``` >輸入 ``` 21 ``` >輸出 ``` 正整數 ``` --- # 練習題 ## 是非題 1. () `elif` 只能使用一次 2. () `if` 是通過條件式產生的布林值作為判斷依據 3. () 以下程式是正確的 ```python=1 a=int(input()) if (a>0): print("a是正整數") ``` 4. () 以下程式是正確的 ```python=1 a=int(input()) b=100 if(a=b): print('correct') ``` 5. () 以下程式是正確的 ```python=1 a=int(input()) b=int(input()) if (a>b): print("a>b") elif(a==b): print("a=b") else: print("a<b") ``` --- ## 練習題 設計一個程式,詢問使用者輸入三個數字,並顯示其中的最大值。 ## 參考資料 > https://steam.oxxostudio.tw/category/python/basic/if.html#a6
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up