前言
if 語句是最簡單的選擇結構。如果滿足條件就執行設定好的操作,不滿足條件就執行其他其他操作。
判斷的定義
- 如果 條件滿足,才能做某件事情,
- 如果 條件不滿足,就做另外一件事情,或者什麼也不做
判斷語句 又被稱為“分支語句”

if...else... 語句,當 if 的條件為 True 時執行 if 下的語句塊,否則執行 else 下語句塊。

注意:if 和 else 語句以及各自的縮排部分共同是一個 完整的程式碼塊


多條件

- 在開發中,使用 if 可以 判斷條件
- 使用 else 可以處理 條件不成立 的情況
- 但是,如果希望 再增加一些條件,條件不同,需要執行的程式碼也不同 時,就可以使用 elif
- 語法格式如下:


注意
- elif 和 else 都必須和 if 聯合使用,而不能單獨使用
- 可以將 if 、 elif 和 else 以及各自縮排的程式碼,看成一個 完整的程式碼塊
elif 的應用場景是:同時 判斷 多個條件,所有的條件是 平級 的
- 在開發中,使用 if 進行條件判斷,如果希望 在條件成立的執行語句中 再 增加條件判斷,就可以使用 if 的巢狀
- if 的巢狀 的應用場景就是:在之前條件滿足的前提下,再增加額外的判斷
- if 的巢狀 的語法格式,除了縮排之外 和之前的沒有區別
- 語法格式如下:

if 的巢狀

總結
if 的三種形式
if

不滿足條件時沒有任何提示
if ... else

if ... elif ... elif ... else
多條件選擇使用

if巢狀
