
選擇結構有單一選擇跟多重選擇,兩者都使用 if 陳述 (if statement) , if 為關鍵字 (keyword) 之一,若是多重選擇 if 須與 elif 或 else 連用。單一選擇,也就是單獨使用 if 陳述如下
if 3 > 5 : print ( "Oh! 3 is bigger than 5!" ) |
條件為 if 後面到冒號的範圍,上例為 3 大於 5 ,如果 3 大於 5 為真,程式就會執行條件後縮排的程式區塊 (block) ,其範圍一直到沒有縮排為止,這裡就可以看到 Python 裡頭縮排的意義。如果 3 大於 5 為假,程式自然跳過條件後的程式區塊,去找區塊後的第一個陳述 (statement) 執行。
if 與 else 連用,條件為真,執行 if 後的程式區塊,條件為假,就執行 else 後的程式區塊
if 3 > 5 : print ( "Oh! 3 is bigger than 5!" ) else : print ( "Not Bad! 3 is not bigger than 5!" ) |
elif 表示其他的條件,形成 if-elif-else 的多重選擇,最後的 else 表示以上皆非
if 3 > 5 : print ( "Oh! 3 is bigger than 5!" ) elif 4 > 5 : print ( "Oh! 4 is bigger than 5!" ) elif 5 > 5 : print ( "Oh! 5 is bigger than 5!" ) elif 6 > 5 : print ( "Of course, 6 is bigger than 5!" ) else : print ( "There is no case :(" ) |
我們將以上寫成完整的範例程式,如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | print () if 3 > 5 : print ( "Oh! 3 is bigger than 5!" ) elif 4 > 5 : print ( "Oh! 4 is bigger than 5!" ) elif 5 > 5 : print ( "Oh! 5 is bigger than 5!" ) elif 6 > 5 : print ( "Of course, 6 is bigger than 5!" ) else : print ( "There is no case :(" ) print () # 《程式語言教學誌》的範例程式 # 檔名:selection.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2012 年 12 月 |
執行結果如下

另舉一例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | print () s = 6 if s = = 3 : print ( "3..." ) elif s = = 4 : print ( "4..." ) elif s = = 5 : print ( "5..." ) elif s = = 6 : print ( "6..." ) else : print ( "There is no case :(" ) print () # 《程式語言教學誌》的範例程式 # 檔名:selection2.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2012 年 12 月 |
這裡的條件為判斷某一變數 (variable) 是否符合某一常數 (constant) ,執行結果如下

複合陳述 (compound statement) 除了選擇結構 (selection structure) 還有重複結構 (repetition structure) ,重複結構也被稱為迴圈 (loop) ,接下來我們就來看看如何使用迴圈吧!
中英文術語對照 | |
---|---|
選擇 | selection |
條件 | condition |
if 陳述 | if statement |
關鍵字 | keyword |
程式區塊 | block |
陳述 | statement |
常數 | constant |
變數 | variable |
複合陳述 | compound statement |
選擇結構 | selection structure |
重複結構 | repetition structure |
迴圈 | loop |
您可以繼續參考
基礎篇
相關目錄
回 Python 入門指南
回 Python 教材
回首頁
參考資料
http://docs.python.org/3.1/tutorial/controlflow.html
http://docs.python.org/3.1/reference/lexical_analysis.html
http://docs.python.org/3.1/reference/simple_stmts.html
http://docs.python.org/3.1/reference/compound_stmts.html
沒有留言:
張貼留言